如何在不引用 json.net 中的数组和记录的情况下序列化对象
How to serialize object without quoting arrays and records in json.net
当使用 Newtonsoft 的 Json.net 序列化我的对象时,我得到:
{"status":"1",
"message":"test",
"records":"[{\"id\":\"1\", \"name\":\"file1\"},
{\"id\":\"2\", \"name\":\"file2\"},
{\"id\":\"3\", \"name\":\"file3\"}]" // I want to get rid of the extra quotes for the array
}
我想要:
{"status":"1",
"message":"test",
"records":[{"id":"1", "name":"file1"},
{"id":"2", "name":"file2"},
{"id":"3", "name":"file3"}] // NOTE: this is an Array of records
}
这是我用来序列化的简化代码:
QHttpResponse tempResponse = new QHttpResponse() { StatusCode = (int)HttpStatusCode.OK, Message = "File found." };
JObject jo = JObject.FromObject(tempResponse);
jo.Add("records",JsonConvert.SerializeObject(jo));
这是 QHttpResponse class:
public class QHttpResponse
{
#region Feilds
/// <summary>
/// Status code of the http response (e.g.:400 = bad request.)
/// </summary>
[JsonProperty("status_code")]
public int StatusCode { get; set; }
/// <summary>
/// Message (Content) of the response.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
#endregion
}
您的问题在这里:
jo.Add("records",JsonConvert.SerializeObject(jo));
你序列化数组并将它添加到 "records" 属性,然后你序列化整个东西因此你得到双重序列化,这就是为什么你有转义的 \"。
尝试:
jo["records"] = arrayData;
稍后当您序列化时,它应该会如您所愿地出现。
当使用 Newtonsoft 的 Json.net 序列化我的对象时,我得到:
{"status":"1",
"message":"test",
"records":"[{\"id\":\"1\", \"name\":\"file1\"},
{\"id\":\"2\", \"name\":\"file2\"},
{\"id\":\"3\", \"name\":\"file3\"}]" // I want to get rid of the extra quotes for the array
}
我想要:
{"status":"1",
"message":"test",
"records":[{"id":"1", "name":"file1"},
{"id":"2", "name":"file2"},
{"id":"3", "name":"file3"}] // NOTE: this is an Array of records
}
这是我用来序列化的简化代码:
QHttpResponse tempResponse = new QHttpResponse() { StatusCode = (int)HttpStatusCode.OK, Message = "File found." };
JObject jo = JObject.FromObject(tempResponse);
jo.Add("records",JsonConvert.SerializeObject(jo));
这是 QHttpResponse class:
public class QHttpResponse
{
#region Feilds
/// <summary>
/// Status code of the http response (e.g.:400 = bad request.)
/// </summary>
[JsonProperty("status_code")]
public int StatusCode { get; set; }
/// <summary>
/// Message (Content) of the response.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
#endregion
}
您的问题在这里:
jo.Add("records",JsonConvert.SerializeObject(jo));
你序列化数组并将它添加到 "records" 属性,然后你序列化整个东西因此你得到双重序列化,这就是为什么你有转义的 \"。
尝试:
jo["records"] = arrayData;
稍后当您序列化时,它应该会如您所愿地出现。