将C#对象转为json字符串,如何处理双引号

时间:2022-09-02 09:32:20

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

我正在使用Newtonsoft.Json将对象解析为json字符串。它会像这样返回一些思考:

{\"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?

它不是一个有效的json字符串我认为,任何人都可以帮我工作?

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:

编辑:这是来自响应fidder TextView的实际json我可以看到:

"{\"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

场景是这样的:我将序列化的json字符串放在web api CreateResponse方法中。我可以在fidder中看到响应字符串,就像我在问题中所说的那样是无效的json

Request.CreateResponse(HttpStatusCode.Created, returnString);

returnString is json string from the serialized ResponseString object

returnString是序列化的ResponseString对象的json字符串

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

我不认为这是一个有效的字符串,我错了吗?

2 个解决方案

#1


3  

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.

根本原因:我的猜测是它是双序列化问题。看来ASP.NET web api 2框架会自动为我们做序列化。这就是为什么我SerializeObject然后Debug.Write(json)字符串,它运作良好。

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.

但是在fiddler调用web API之后,web API返回了无效的json(\“)响应,如上所述。这在其他客户端如ios,android设备上也是如此。

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.

因为web api为我做了序列化,我还做了一个额外的显式序列化,字符串json = JsonConvert.SerializeObject(rs);这意味着我运行另一个不需要的parseJson。

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.

根据我的问题,我只是在CreateResponse方法中直接放置未序列化的对象。 Request.CreateResponse(HttpStatusCode.Created,rs);它为fidder和其他客户端返回有效的json。

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

我如何解决这个问题: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);

#2


0  

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 :

我怀疑你在调试器中看到了这一点。它不是实际的字符串,只是visual studio调试器中的表示。例如,我测试了这段代码:

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 : 将C#对象转为json字符串,如何处理双引号

视觉工作室观察窗口中显示的str值如何:

how the actual string printed in console : 将C#对象转为json字符串,如何处理双引号

如何在控制台中打印实际字符串:

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

结论:Newtonsoft.Json应该将对象转换为正确的json字符串表示。无需进一步努力。

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).

回应你的编辑,我有一种强烈的感觉,它再次只是在另一个工具(提琴手)中的相同表现形式。这个“是许多编程平台中双引号的表示,因为普通的双引号(”)被认为是字符串的结尾/开头(只是说,如果你错过了那个信息)。

#1


3  

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.

根本原因:我的猜测是它是双序列化问题。看来ASP.NET web api 2框架会自动为我们做序列化。这就是为什么我SerializeObject然后Debug.Write(json)字符串,它运作良好。

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.

但是在fiddler调用web API之后,web API返回了无效的json(\“)响应,如上所述。这在其他客户端如ios,android设备上也是如此。

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.

因为web api为我做了序列化,我还做了一个额外的显式序列化,字符串json = JsonConvert.SerializeObject(rs);这意味着我运行另一个不需要的parseJson。

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.

根据我的问题,我只是在CreateResponse方法中直接放置未序列化的对象。 Request.CreateResponse(HttpStatusCode.Created,rs);它为fidder和其他客户端返回有效的json。

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

我如何解决这个问题: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);

#2


0  

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 :

我怀疑你在调试器中看到了这一点。它不是实际的字符串,只是visual studio调试器中的表示。例如,我测试了这段代码:

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 : 将C#对象转为json字符串,如何处理双引号

视觉工作室观察窗口中显示的str值如何:

how the actual string printed in console : 将C#对象转为json字符串,如何处理双引号

如何在控制台中打印实际字符串:

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

结论:Newtonsoft.Json应该将对象转换为正确的json字符串表示。无需进一步努力。

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).

回应你的编辑,我有一种强烈的感觉,它再次只是在另一个工具(提琴手)中的相同表现形式。这个“是许多编程平台中双引号的表示,因为普通的双引号(”)被认为是字符串的结尾/开头(只是说,如果你错过了那个信息)。