Turn C# object to json string, how to handle double quotation -
i'm using newtonsoft.json parse object json string. returns somethink this:
{\"code\":-1,\"idname\":\"empty\",\"idvalue\":0,\"message\":\"failed,can not read object body\"}
it not valid json string think, can work me out?
what want this:
{"code":-1,"idname":"empty\",\"idvalue\":0,\"message\":\"failed,can not read object 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: actual json response fidder textview can see:
"{\"code\":-1,\"idname\":\"empty\",\"idvalue\":0,\"message\":\"failed,can not read object body\"}"
the scenario this: put serialized json string in web api createresponse method. can see response string in fidder said in question not valid json
request.createresponse(httpstatuscode.created, returnstring);
returnstring
json string serialized responsestring
object
i donot think valid string , wrong?
finally, fix this. share guys.
root cause:
guess is double serialization issue. seems asp.net web api 2 framework serialize automatically us. , why serializeobject
, debug.write(json)
string, works well.
string json = jsonconvert.serializeobject(rs); debug.write(json);
but after fiddler invoke web api, web apireturned response invalid json(\") said above. happened same on other clients such ios, android devices.
because web api serialization me, , explicit serialization string json = jsonconvert.serializeobject(rs);
means run parsejson not needed.
per question here, directly put object not serialized in createresponse
method. request.createresponse(httpstatuscode.created, rs);
, returns valid json fidder , other clients.
how fix 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 controller
responsestring rs = new responsestring(); rs = commonutility.formatresponsestring(0, "pacelid", returnpacelid, "succeed,created items in db success"); return request.createresponse(httpstatuscode.created, rs);
Comments
Post a Comment