Tag Archives: json

Such a simple serialization system.text.json.serialization also reports an error?

Consulting area

kofifus:

I am going to switch json.net in the project to the native system. Text. JSON , but I encountered an unexpected error. The test code is as follows:


using System.Text.Json.Serialization;
using Newtonsoft.Json;

public class C {
  public C(string PracticeName) { this.PracticeName = PracticeName; }
  public string PracticeName;
}

var x = new C("1");
var json = JsonConvert.SerializeObject(x); // returns "{\"PracticeName\":\"1\"}"

var x1 = JsonConvert.DeserializeObject<C>(json); // correctly builds a C

var x2 = System.Text.Json.Serialization.JsonSerializer.Parse<C>(json);

The last line of the above code will report:


Exception thrown: 'System.NullReferenceException' in System.Text.Json.dll Object reference not set to an instance of an object.

What did I do wrong?

I found that this problem can be solved by parameterless constructor , but doing so will put the cart before the horse. Is there a flexible way to realize the simple functions that can be realized by JSON. Net .

Answer area

Christian Gollhardt:

In the . Net core 3.0 stage, the development of system. Text. JSON has not been completely completed. At present, only nonparametric constructor is supported, which may be supported in the future.

If you are migrating the old version to . Net core 3.0 , I still suggest you use newtonsoft. JSON .

    MVC

Install the microsoft.aspnetcore.mvc.newtonsoftjason package from nuget and inject it into the Services container.


services.AddMvc().AddNewtonsoftJson();

    SignalR:

InstallMicrosoft.AspNetCore.SignalR.Protocols.NewtonsoftJson package from Nuget


//Client
new HubConnectionBuilder()
.WithUrl("/chatHub")
.AddNewtonsoftJsonProtocol(...)
.Build();

//Server
services.AddSignalR().AddNewtonsoftJsonProtocol(...);

In this way, you can use json.net in . Net core 3.0 .

user11400447:

To solve this problem, you must make two changes:

praccename

    1. should be made into an attribute, not a field. Use a parameterless constructor

I wrote a console program, in which C1 is converted through newtonsoft. JSON , and C2 is converted through system. Text. JSON .


using Newtonsoft.Json;

namespace TestJsonParse
{
    class Program
    {
        static void Main(string[] args)
        {
            var c1 = new C1("1");
            var json1 = JsonConvert.SerializeObject(c1); // returns "{\"PracticeName\":\"1\"}"
            var x1 = JsonConvert.DeserializeObject<C1>(json1); // correctly builds a C1

            var c2 = new C2();
            string json2 = "{\"PracticeName\":\"1\"}";
            var x2 = System.Text.Json.Serialization.JsonSerializer.Parse<C2>(json2); // correctly builds a C2
        }

        class C1
        {
            public C1(string PracticeName) { this.PracticeName = PracticeName; }
            public string PracticeName;
        }

        class C2
        {
            public C2() { }
            public string PracticeName { get; set; }
        }
    }
}

Comment area

Times have changed. I’ve finished system.text.jason, and then I used the latest. Net 5 digression code.


namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\"PracticeName\":\"1\"}";

            //json.net
            var x1 = JsonConvert.SerializeObject(json);

            //System.Text.Json
            var x2 = System.Text.Json.JsonSerializer.Deserialize<C>(json);

        }
    }

    public class C
    {
        public C(string PracticeName) { this.PracticeName = PracticeName; }
        public string PracticeName;
    }
}

The result is…. Continue to report errors…

What else can I say

Json: struct field readyReplicas has json tag but is not exported [How to Solve]

type MeshStatus struct {
	// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
	// Important: Run "make" to regenerate code after modifying this file
	AvailableReplicas int `json:"available_replicas,omitempty"`
	readyReplicas     int `json:"ready_replicas,omitempty"`
	Replicas          int `json:"replicas,omitempty"`
}

error: struct field readyReplicas has json tag but is not exported
Cause of the error readyReplicas does not have a capitalization at the beginning ReadyReplicas

Typeerror: write() argument must be STR, not bytes and the method of writing binary file in Python 3

Python 2 writes binary file randomly:

with open('/python2/random.bin','w') as f:
    f.write(os.urandom(10))

However, using Python 3 will report an error:

TypeError:must be str, not bytes

The reason is: Python 3 adds a new parameter named encoding to the open function, and the default value of this new parameter is “UTF-8”. In this way, when the read and write operations are carried out on the file handle, the system requires the developer to pass in the instance containing Unicode characters instead of the byte instance containing binary data.

resolvent:

Use binary write mode (“WB”) to open the file to be operated, instead of using character write mode (“W”) as before.

The method of adapting both Python 3 and python 2 is as follows

with open('python3/rndom.bin','wb') as f:
    f.write(os.urandom(10))

There is a similar problem when the file reads data. The solution to this problem is similar: open the file in ‘RB’ mode (binary mode) instead of ‘R’ mode.

Reproduced in: https://www.cnblogs.com/circleyuan/p/10350202.html

[Solved] TypeError: Converting circular structure to JSON – JSON.stringify

When using the json.stringify method to convert a string, an error typeerror: converting circular structure to JSON will be reported

Reason: there is a circular reference to itself in the object;

For example:

let test = { a: 1, b: 2 };
test.c = test; // Circular references
JSON.stringify(test); // report an error

Solution:
the following JSON_ STR is the converted String of JSON. Stringify

var cache = [];
var json_str = JSON.stringify(json_data, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            return;
        }
        cache.push(value);
    }
    return value;
});
cache = null;	//release cache

[Solved] JSON parse error: Unexpected character (‘‘‘ (code 39)): was expecting double-quote to star

Warning: [http-nio-8080-exec-6] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotReadable Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character (''' (code 39)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
 at [Source: (PushbackInputStream); line: 1, column: 3]

Error reason: the format of JSON parameter is wrong
error screenshot

single quotation mark ‘and double quotation mark’ error, which is modified to

perfect solution

[Solved] Interface automation test: JSON parse error

1.error:
{
“title” : “Bad Request”,
“status” : 400,
“detail” : “JSON parse error: Unrecognized token ‘username’: was expecting (‘true’, ‘false’ or ‘null’); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘username’: was expecting (‘true’, ‘false’ or ‘null’)\n at [Source: (PushbackInputStream); line: 1, column: 10]”,
“path” : “/getToken”,
“message” : “error.http.400”
}
2.codes

import requests


url = 'http://10.165.153.210/getToken'
headers = {
    'Content-Type': 'application/json'
}
payload = {
    'username': 'pad_view',
    'password': '6368da1213cd4c4538128a0e9acd0288'
}
res = requests.post(url=url,method='post', data=payload, headers=headers)
print(res.text)

3. Reasons

When you request to pass parameters, the JSON string and dictionary look the same, but the background serialization format is different. Therefore, a JSON parsing error will be reported when data is passed in

4. Solutions

Convert dictionary object to JSON string

4.1 import JSON

import json

4.2 convert dictionary object to JSON string

payload = json.dumps({
    'username': 'username',
    'password': 'password'
})

4.3 complete modification code, as follows

import requests
import json  # import json


url = 'http://10.165.153.210/getToken'
headers = {
    'Content-Type': 'application/json'
}
# Convert a dictionary object into a json string, using the json.dumps() method
payload = json.dumps({
    'username': 'pad_view',
    'password': '6368da1213cd4c4538128a0e9acd0288'
})
res = requests.post(url=url,method='post', data=payload, headers=headers)
# Print the response message
print(res.text)

How to Converte Java objects to jsonnode in Jackson (Four Methods)

Can I convert Java objects to jsonnode objects directly
the only way to solve this problem is to convert the Java object to string and then to jsonnode

ObjectMapper mapper = new ObjectMapper();
//Method 1
String json = mapper.writeValueAsString(Java Object);
JsonNode jsonNode = mapper.readTree(json);
//Method 2
JsonNode jsonNode = mapper.valueToTree(Java Object);
//Method 3
JsonNode jsonNode = mapper.convertValue(Java Object, JsonNode.class);

Examples

	/**
	 * Converting Java objects to JsonNode in Jackson
	 *
	 * @param object
	 * @return
	 */
	public static JsonNode getJsonNode(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.convertValue(object, JsonNode.class);

	}

Springmvc Content type ‘application/json‘ not supported

In the practice of spring MVC, many people may encounter this annoying problem, it took a long time to solve, the code is right, but he just reported an error
content type ‘application/JSON’ not supported
I have found many articles on the Internet and used many methods, but they can’t solve this problem
finally, I remembered if I didn’t add the jar package required by JSON in lib, so I tried it… It was a success indeed
the following is my method

because I have added it, so here you can see that there are three jar packages in my lib package,
just add these three packages~~~

The tree component in easyUI does not display data or displays undefined solutions

In recent days, I have learned easyUI and used the tree component. After n days of pain, I finally came out. Now I will summarize some problems.

1. In the official demo, all the data is taken from the. JSON file. In practical application, it is obviously impossible to do so. If you want to take it from the database, then the problem is, how to get it?There’s no explanation in the official demo, and I haven’t found any results after searching online for a long time

Methods 1:Ajax is fetched, after the web interface is loaded, the Ajax is called, and the value is spliced from the background in the database, and spliced into JSON. There are many methods of splicing. Here is not enumerated. After the completion of the mosaic, JSON is written back by response writer. In JS, the data parameter of tree is the returned JSON (time reason, this method is not tested, and the theory is feasible).

Method 2: root method 1 is similar: the following is the code

HTML code of tree:

<ul id="department_tree" class="easyui-tree"></ul>

JS code of tree:

/**
 * @argument Fetching data from a tree by URL
 * @author ZHENGWEI
 * @date 2015-5-8
 * @version 1.0
 */
$(document).ready(function(){
	/* Called when loading is complete*/
	$("#department_tree").tree({
		/*JSON spliced address*/
		url:'CompanyStaffAction!listCompanyDepartment.action',
		/*Linked lines*/
		lines:true,
		/*animation effect*/
		animate:true
	});
})

The URL is the action returned to JSON in the background, and the code is as follows

/**
	 * Search company's department information
	 * @author ZHENGWEI
	 * @throws JSONException 
	 * @throws IOException 
	 * @date 2015-5-7
	 */
	public String listCompanyDepartment() throws JSONException, IOException{
		//Set the encoding format to prevent Chinese characters from being garbled
		response.setCharacterEncoding("UTF-8");
		//return company department information
		List<CompanyDepartmentInfo> companyDepartmentInfoList = this.companyStaffService.listCompanyDepartment();
		// Declare the JSONArray object and build the tree
		JSONArray jsonChildTreeArray = new JSONArray();
		//condemn empty
		if(companyDepartmentInfoList.size() != 0){
			for(CompanyDepartmentInfo companyDepartmentInfo:companyDepartmentInfoList){
				JSONObject jsonChildInfoObject = new JSONObject();
				jsonChildInfoObject.put("id", '"'+companyDepartmentInfo.getDepartmentId()+'"');
				jsonChildInfoObject.put("text", companyDepartmentInfo.getDepartmentName());
				jsonChildTreeArray.put(jsonChildInfoObject);
			}
		}
		JSONObject jsonDepartmentTree = new JSONObject();
		jsonDepartmentTree.put("id", "0");
		jsonDepartmentTree.put("text", "CompanyDepartmentTree");
		jsonDepartmentTree.put("state", "open");
		// turn the jsonChildTreeArray into a child node
		jsonDepartmentTree.put("children", jsonChildTreeArray);
		//string type, add '[]' to JSON
		String treeData = jsonDepartmentTree.toString();
		treeData = "["+treeData+"]";
		// Declare PrintWriter variable to pass back JSON
		PrintWriter out = response.getWriter();
		out.write(treeData);
		return null;
	}

It must be noted that,

After the encapsulation of JSON, make sure to print it to see if there is a [] symbol package outside of JSON, otherwise tree can’t read the data!!!!

The final results are as follows:

 

 

It’s a very hard process… It’s tears when I talk too much, and many problems on the Internet can’t reach the point. I’ve thought about it for many days, and I hope that students who study in the future will avoid detours