Is it possible to tell JSON.NET I have a string with JSON data? E.g. I have a class like this:
public class Foo
{
public int Id;
public string RawDat
You need a converter to do that, here is an example:
public class RawJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return typeof(string).IsAssignableFrom(objectType);
}
public override bool CanRead
{
get { return false; }
}
}
Then decorate your class with it:
public class Foo
{
public int Id;
[JsonConverter(typeof(RawJsonConverter))]
public string RawData;
}
Then, when you use:
var json = JsonConvert.SerializeObject(foo,
new JsonSerializerSettings());
Console.WriteLine (json);
This is your output:
{"Id":5,"RawData":{"bar":42}}
Hope it helps
Edit: I have updated my answer for a more efficient solution, the previous one forced you to serialize to then deserialize, this doesn't.
You can use another property to deserialize the object property json.
public class Foo
{
public int Id;
public string RawData;
private object thisObject;
public object ThisObject
{
get
{
return thisObject ?? (thisObject = JsonConvert.DeserializeObject<object>(RawData));
}
}
}
It is possible, that using JRaw
could be more sutable and comapct solution
see this post