Creating a double serialized JSON object in REST SOE C#

为君一笑 提交于 2019-12-13 00:16:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!