Question

I have a json string looking something like this:

{
    "Bar": { 
        "Pressure":42,
        "ServesDrinks":false
    },
    "Baz":[
        {
            "Pressure":9001,
            "ServesDrinks":true
        },
        {
            "Pressure":0,
            "ServesDrinks":false
        }
    ]
}

And I would like to de-serialize this into a class looking something like this:

public class Foo
{
    public Bar Bar { get; set; }

    /// <summary>
    /// Raw serialized (un-de-serialized) json string of the Baz list  
    /// </summary>
    public string Baz { get; set; }
}

Basically not de-serializing the Baz value and instead storing the raw string. I.e. I want the Baz string value after serialization to be:

"[{\"Pressure\":9001,\"ServesDrinks\":true},{\"Pressure\":0,\"ServesDrinks\":false}]"

I am using Json.Net but have not managed to figure out how to do this. In the ideal case I would just like to put a magic attribute on my Baz property that retains the raw json.

I have seen a very similar question here: Partially deserialize with JSON.NET, keeping some fields raw

But I did understand how to go with that JObject approach.

(If it is of any help, I know that the data I want to retain is a list)

Thankful for any help!

Was it helpful?

Solution

Based on the answer to the other question, it seems that the solution in JSON.Net for cases like this is to use the appropriate J* type and use their ToString() and Parse() methods to work with the JSON string.

For JS lists, the appropriate type seems to be JArray, not JObject, which is used for {} style Javascript objects.

Please note that I know little about JSON.Net, and perhaps there is a different solution which would avoid the need to use Parse() and ToString() everywhere. Somebody with a better knowledge of that library might give a better answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top