I have a JSON string
{
"F1":
{
"BF1":"BV1",
"BF2":"BV2"
},
"F2":"BF1"
}
and I wish to assign it to an object of this type
public class MyType
{
public string F1 {get;set;}
public string F2 {get;set;}
}
in other words, I need to convert JSON to an object, but the inner object is to be assigned as a JSON string
the simpliest way is
var jObj = JObject.Parse(json);
MyType myType = new MyType
{
F1 = jObj["F1"].ToString(),
F2 = jObj["F2"].ToString()
};
or if you don't want indented formating
MyType myType = new MyType
{
F1 = JsonConvert.SerializeObject(jObj["F1"]),
F2 = (string) jObj["F2"];
};
of if you like a hard way
MyType myType = JsonConvert.DeserializeObject<MyType>(json,new MyTypeJsonConverter());
public class MyTypeJsonConverter : JsonConverter<MyType>
{
public override MyType ReadJson(JsonReader reader, Type objectType, MyType existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var jObj = JObject.Load(reader);
return new MyType
{
F1 = JsonConvert.SerializeObject(jObj["F1"]),
F2 = (string)jObj["F2"]
};
}
// or maybe this
// public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, MyType value, JsonSerializer serializer)
{
var val = new
{
F1 = JObject.Parse(value.F1),
F2 = value.F2
};
writer.WriteRaw(JsonConvert.SerializeObject(val, Newtonsoft.Json.Formatting.Indented));
}
}
or if you have many properties that should deserialize common way
MyType myType = JsonConvert.DeserializeObject<MyType>(json);
public class MyType
{
[JsonConverter(typeof(MyTypePropertyJsonConverter))]
public string F1 { get; set; }
public string F2 { get; set; }
}
public class MyTypePropertyJsonConverter : JsonConverter<string>
{
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return JsonConvert.SerializeObject(JToken.Load(reader));
}
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
{
writer.WriteRawValue(value);
}
}