问题
I'm not sure if I'm double-serializing my JSON object, but the output results in an unwanted format. I'm exposing the REST endpoint via an ArcGIS Server Object Extension (REST SOE). I've also recently implemented JSON.Net which essentially allowed me to remove several lines of code.
So here is the handler, which is the core piece creating the data for the service (for you non GIS peeps).
private byte[] SearchOptionsResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = null;
JsonObject result = new JsonObject();
// Towns
DataTable dataTableTowns = GetDataTableTowns();
String jsonStringTowns = JsonConvert.SerializeObject(dataTableTowns);
result.AddString("Towns", jsonStringTowns);
// GL_Description
DataTable dataTableGLDesc = GetDataTableGLDesc();
String jsonStringGLDesc = JsonConvert.SerializeObject(dataTableGLDesc);
result.AddString("GLDesc", jsonStringGLDesc);
return Encoding.UTF8.GetBytes(result.ToJson());
}
The result is ugly scaped JSON:
{
"Towns": "[{\"Column1\":\"ANSONIA\"},{\"Column1\":\"BETHANY\"},{\"Column1\":\"BLOOMFIELD\"}]",
"GLDesc": "[{\"Column1\":\"Commercial\"},{\"Column1\":\"Industrial\"},{\"Column1\":\"Public\"}]"
}
Is it because I'm double serializing it somehow? Thanks for looking this over.
回答1:
Yes, you are double serializing it. It's right there in your code.
For each of your data tables, dataTableTowns
and dataTableGLDesc
, you are calling JsonConvert.SerializeObject()
to convert them to JSON strings, which you then add to a result JsonObject
. You then call ToJson()
on the result, which presumably serializes the whole thing to JSON again.
JsonObject
is not part of Json.Net, while JsonConvert
is, so I would recommend using one or the other. Generally, you just want to accumulate everything into a single result object and then serialize the whole thing once at the end. Here is how I would do it with Json.Net using an anonymous object to hold the result:
var result = new
{
Towns = GetDataTableTowns(),
GLDesc = GetDataTableGLDesc()
};
string json = JsonConvert.SerializeObject(result);
return Encoding.UTF8.GetBytes(json);
Here is the output:
{
"Towns":[{"Column1":"ANSONIA"},{"Column1":"BETHANY"},{"Column1":"BLOOMFIELD"}],
"GLDesc":[{"Column1":"Commercial"},{"Column1":"Industrial"},{"Column1":"Public"}]
}
来源:https://stackoverflow.com/questions/20013632/creating-a-double-serialized-json-object-in-rest-soe-c-sharp