Question about Json Deserialization (Json.NET)

Hi guys!

I have a json string as follow:

{"Name":"John Smith", "Age":30,"More":{"Country":"USA","City":"Los Angeles"}} 

Is it possible to deserialize it to an object as this?

public class Person { public string Name { get; set; } public int Age { get; set; } public string More { get; set; } } 

I need to do this but I am not allowed to change More data type to a Dictionary. I need the content of the More string to be

{"Country":"USA","City":"Los Angeles"} 

Im using Json.NET to try to deserialize it:

JsonConvert.DeserializeObject<Person>(json_string); 

but im getting an JsonReaderException because the serializer expect an string but finds an object in the json string value corresponding to More:

Newtonsoft.Json.JsonReaderException: Error reading string. Unexpected token: StartObject. Path 'More', line 1, position 40. Result StackTrace: at Newtonsoft.Json.JsonReader.ReadAsStringInternal() at Newtonsoft.Json.JsonTextReader.ReadAsString() at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value) 

Can anyone show me the path of how to do this, if possible. May be using custon JsonConverter?

by AnnoyingAxolotl via /r/csharp

Leave a Reply