0

I have a question about inserting a json formatted string into a json structure and having the final version be a combined JSON formatted string that can be serialized into a JSON structure. I am using the newtonsofts Json.NET

I have the following JSON structure:

public class ResponseJson
{
    [JsonProperty(PropertyName = "header")]
    public ResponseHeader responseHeader { get; set; }

    [JsonProperty(PropertyName = "results")]
    public string responseResults { get; set; }
}

public class ResponseHeader
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }

    [JsonProperty(PropertyName = "version")]
    public string version { get; set; }
}

In the code, I do the following:

        ResponseJson responseJson = new ResponseJson();
        responseJson.responseHeader = new ResponseHeader()
        {
            name = A_NAME,
            version = A_VERSION
        };
        responseJson.responseResults = resultJson;

        return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

resultJson is a properly formatted JSON string (in this case, an array of objects, but could be anything JSON formatted). Right now, if i execute the code, I get the following (which is expected, since "results" is declared as a string):

{
    "header":
        {
            "name":"abcd",
            "version":"1.0"
        },
    "results":
        "[{\"data\":{\"level\":\"100\"},\"code\":{\"value\":\"JBC\",\"type\":\"ev\"},\"time\":{\"start\":\"20\",\"end\":\"101\"}}]"
}

what I do need as an output is:

{
    "header":
        {
            "name":"abcd",
            "version":"1.0"
        },
    "results":
        [
            {
                "data":
                    {
                        "level":"100"
                    },
                "code":
                    {
                        "value":"JBC",
                        "type":"ev"
                    },
                "time":
                    {
                        "start":"20",
                        "end":"101"
                    }
            }
        ]
}
3
  • Your code doesn't compile. In the lineresponseJson.responseResults = resultJson the variable resultJson is undefined. What is it supposed to be? Commented Dec 9, 2015 at 21:32
  • type string. thank you Commented Dec 9, 2015 at 21:34
  • so, you need to do the opposite of what your title asks for, because you are currently correctly inserting a json string into another json string. Commented Dec 9, 2015 at 22:51

1 Answer 1

1

While you don't explain how you create your resultJson variable, it's implied from your code that you are double-serializing your results: you compute an array of "result" classes, serialize them to a JSON string, store the string in your ResponseJson class, and them serialize that in turn. The embedded JSON string then gets escaped as per the JSON standard, which is what you are seeing.

You need to avoid double-serializing your data, for instance by using the following data model:

public class ResponseJson<T>
{
    [JsonProperty(PropertyName = "header")]
    public ResponseHeader responseHeader { get; set; }

    [JsonProperty(PropertyName = "results")]
    public T responseResults { get; set; }
}

public static class ResponseJson
{
    public static ResponseJson<T> Create<T>(T responseResults, ResponseHeader responseHeader)
    {
        return new ResponseJson<T> { responseResults = responseResults, responseHeader = responseHeader };
    }
}

public class ResponseHeader
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }

    [JsonProperty(PropertyName = "version")]
    public string version { get; set; }
}

Then you would do:

        var results = GetResults(); // Get your result data
        var responseJson = ResponseJson.Create(results, new ResponseHeader()
        {
            name = A_NAME,
            version = A_VERSION
        });

        return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

If for whatever reason you must embed a previously serialized JSON string as JSON rather than as a string literal, you'll need to re-parse it back to a JToken:

        string resultJson = GetResultJson(); // Get result json string.
        var responseJson = ResponseJson.Create(JToken.Parse(resultJson), new ResponseHeader()
        {
            name = A_NAME,
            version = A_VERSION
        });

        return JsonConvert.SerializeObject(responseJson, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

Json.NET will include the JToken in your outer JSON as nested JSON rather than as a string literal.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much for your reply. I suppose that I should have made it clearer that i cant assume what the format of 'resultJson' (or 'results' as you called it) will be. all I can assume is that its a properly formatted JSON string. Your solution requires me to know what it is. I will make an update to my original equestion
@concentriq - I modified the solution so that responseResults can be implicitly typed. Or do you have some code constraint that requires that responseResults was previously serialized as JSON?
"re-parse it back to a JToken" is the answer I was looking for in this situation. string is all i have to work with here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.