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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…