Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Raw json string in Newtonsoft.Json Library

I have json like this

{
    "name": "somenameofevent",
    "type": "event",
    "data": {
        "object": {
            "age": "18",
            "petName": "18"
        },
        "desct": {
        }
    }
}

and I have 2 objects like this

public class CustEvent
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("type")]
    public string EventType{ get; set; }
    [JsonProperty("data")]
    public SomeData Data{ get; set; }
}

public class SomeData
{
    [JsonProperty("object")]
    public String SomeObject { get; set;}
    [JsonProperty("dsct")]
    public String SomeDesct { get; set; }
}

I use to parse json to object Newtonsoft.NET library. And how i can get RAW JSON into SomeObject , SomeDesct properties ? In JSON "data.object ..." are complex object and i want to get only RAW JSON String to those properties. Can you help me ?

like image 265
dscherbak Avatar asked May 25 '12 15:05

dscherbak


2 Answers

You don't need to write any converters, just use the JRaw type as follows:

public class SomeData
{
    [JsonProperty("object")]
    public JRaw SomeObject { get; set;}
    [JsonProperty("dsct")]
    public JRaw SomeDesct { get; set; }
}

Then you can access the raw value by checking the .Value property:

var rawJsonDesct = (string)data.SomeDesct.Value;

If you want to retain the string signature, just serialize the JSON to a hidden property and have the string conversion in the accessor call instead.

like image 60
chakrit Avatar answered Oct 07 '22 10:10

chakrit


You have to write a custom converter class (derived from Newtonsoft.Json.JsonConverter) which instructs the deserializer to read the whole object and to return the JSON string for the object.

Then you have to decorate the property with the JsonConverter attribute.

[JsonConverter(typeof(YourCustomConverterClass))]
public string SomeObject { get; set; }

There are good tutorials on the web on how to create custom converters, but - for your convenience - the core of your converter might look like this:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    return JObject.Load(reader).ToString();
}

This method reads a complete JSON object but returns the serialized version of the object as string. There is a bit of overhead because the object is deserialized to a JObject and then serialized again, but for me it's the easiest way to do this. Maybe you have a better idea.

like image 36
fero Avatar answered Oct 07 '22 10:10

fero