Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Newtonsoft.Json to parse object to json string. It returns somethink like this:

{\"code\":-1,\"idName\":\"empty\",\"idValue\":0,\"message\":\"Failed,can not read object from body\"}

it is not a valid json string i think, anyone can work me out?

What I want is something like this:

{"code":-1,"idName":"empty\",\"idValue\":0,\"message\":\"Failed,can not read object from body\"}  

public static class CommonUtility
{
    // format response string
    public static string 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;

        string json = JsonConvert.SerializeObject(rs);
        return json;
    }
}

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

EDIT: this is actual json from the response fidder TextView I can see:

"{\"code\":-1,\"idName\":\"empty\",\"idValue\":0,\"message\":\"Failed,can not read object from body\"}"

the scenario is this: I put the serialized json string in web api CreateResponse method. I can see the response string in fidder like I said in the question which is not valid json

Request.CreateResponse(HttpStatusCode.Created, returnString);

returnString is json string from the serialized ResponseString object

I donot think it is a valid string , am I wrong?

like image 285
max Avatar asked Mar 10 '14 06:03

max


2 Answers

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);
like image 76
max Avatar answered Sep 20 '22 12:09

max


I suspect you saw that in debugger. It isn't the actual string, just representation in visual studio debugger. For example, I tested with this code :

private static void Main(string[] args)
{
    var station = new Station {Name = "Duren Kalibata", LastTemperature = 45, MostRecentDate = DateTime.Now};
    var str = JsonConvert.SerializeObject(station);
    Console.WriteLine(str);
}

how str value shown in visual studio watch window : enter image description here

how the actual string printed in console : enter image description here

Conclusion : Newtonsoft.Json should've converted the object to it's correct json string representation. No further effort needed.

UPDATE :

Responding to your edit, I have a strong feeling that it is, again, just same representation in another tool (fiddler). This \" is representation of double-quotes in many programming platform, because plain double-quotes (") is considered end/beginning of string (just saying, in case you missed that info).

like image 28
har07 Avatar answered Sep 19 '22 12:09

har07