Json.Net: Deserilization With Double Quotes

Json.NET: Deserilization with Double Quotes

It looks like HttpUtility.JavaScriptStringEncode might solve your issue.

HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))

Newtonsoft.JSON chokes on deserializing object that's surrounded by double quotes in an array

Imagine you take an object, and serialize it as JSON. You get a string, right? So if you add that string to a list and serialize the list, you get something like your JSON above.

This is because of this part of your Serialize code: .Select(Serialize). This step doesn't seem necessary at all.

Removing that, we get this:

public void SaveData(IReadOnlyCollection<IUserData> userData)
{
File.WriteAllText(_userDataFile, JsonConvert.SerializeObject(userData, Formatting.Indented));
}

private static string Serialize(IUserData userData) => JsonConvert.SerializeObject(new UserDataJson(userData));

And this code should now work to deserialize the resultant JSON:

var result = JsonConvert.DeserializeObject<List<UserDataJson>>(File.ReadAllText(_userDataFile));

Try it online

Double quotes issue with Newtonsoft.json.jsonserializer

What you're seeing is a verbatim string literal, where the quotes must be escaped by doubling them. There is nothing wrong with the output, it's just showing double quotes in the debugger, but if you were to write it to a file, or send it to an API, they would not be doubled up.

Edit: See this question for more context. Apparently all strings in VB.NET are verbatim string literals: How to do a verbatim string literal in VB.NET?

Tell Json.Net to write a single-quote rather than a double quote when serializing objects

Yes, this is possible. If you use a JsonTextWriter explicitly instead of using JsonConvert.SerializeObject(), you can set the QuoteChar to a single quote.

var obj = new { key = "value" };

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.QuoteChar = '\'';

JsonSerializer ser = new JsonSerializer();
ser.Serialize(writer, obj);
}

Console.WriteLine(sb.ToString());

Output:

{'key':'value'}

Fiddle: https://dotnetfiddle.net/LGRl1k

Keep in mind that using single quotes around keys and values in JSON is considered non-standard (see JSON.org), and may cause problems for parsers that adhere strictly to the standard.

Unwanted double quotes in json

MSDN documentation for JavaScriptSerializer class actually recommends the following:

Json.NET should be used [for] serialization and deserialization.

JSON.NET library became de-facto standard for working with JSON in .NET, for example, it is a default serializer that is used with ASP.NET Web API (link).

Here is how you can re-write your code to use JSON.NET (be sure to add Newtonsoft.Json nuget package to your solution):

public static void Main()
{
var result = SerializeMessages();
Console.WriteLine(result);
}

public static string SerializeMessages()
{
var listOfMessages = new List<Message>
{
new Message("lala1"),
new Message("lala2")
};

return JsonConvert.SerializeObject(listOfMessages);
}

Turn C# object to json string, how to handle double quotation

finally, fix this. share with you guys.

Root Cause:

My guess is that it is the double serialization issue.
It seems ASP.NET web api 2 framework will do the serialize automatically for us. and that is why I SerializeObject and then Debug.Write(json) the string, it works well.

string json = JsonConvert.SerializeObject(rs);     
Debug.Write(json);

but after fiddler invoke the web API, web APIreturned response with invalid json(\") as i said above. this happened the same on other clients such as ios, android devices.

because the web api do the serialization for me, and i do an extra explicit serialization also string json = JsonConvert.SerializeObject(rs); that means i run another parseJson which is not needed.

per my question here, i just directly put the object which is not serialized in the CreateResponse method. Request.CreateResponse(HttpStatusCode.Created, rs); And it returns valid json for the fidder and other clients.

How do i fix this problem:
Request.CreateResponse(HttpStatusCode.Created, rs);

public static class CommonUtility
{
// format response string
public static ResponseString FormatResponseString(int code, string idName, long idValue, string message)
{
ResponseString rs = new ResponseString();
rs.code = code;
rs.idName = idName;
rs.idValue = idValue;
rs.message = message;

return rs ;
}
}

public class ResponseString
{
public int code;
public string idName;
public long idValue;
public string message;
}

and in the controller

ResponseString rs = new ResponseString();
rs = CommonUtility.FormatResponseString(0, "pacelId", returnPacelId, "Succeed,created items in db success");
return Request.CreateResponse(HttpStatusCode.Created, rs);


Related Topics



Leave a reply



Submit