I have an application that serializes an object and sends a JSON string value as below.
public class Rootobject
{
public int MessageState { get; set; }
public object Message { get; set; }
public object HeaderId { get; set; }
}
public class Message
{
public string FName { get; set; }
public string LName { get; set; }
public string Address { get; set; }
}
Rootobject ro = new Rootobject();
ro.HeaderId = "HID";
ro.MessageState = 0;
ro.Message = new Message() { FName = "john", LName = "Doe", Address = "123456" };
string x = JsonConvert.SerializeObject(ro);
This x
value is sent to another application and it is deserialized as below.
public class Rootobject1
{
public int MessageState { get; set; }
public object Message { get; set; }
public object HeaderId { get; set; }
}
public class Message1
{
public string FName { get; set; }
public string LName { get; set; }
public string Address { get; set; }
}
var y = JsonConvert.DeserializeObject<Rootobject1>(receivedMsg);
Here the nested object is not getting deserialized for me and is just a JObject
.
How can I deserialize the nested object? Kindly help.
Thanks.
When the library tries to deserialize the message it does not know what type it should be. The Json will just be a tree of properties, there is nothing to indicate that Message
should be deserialized to a Message1
. Json will inspect the Rootobject1
to figure out the various types it should use, but if you only have object
-property there is no type information to go on.
There are a few solutions
public Message1 Message { get; set; }
This is by far the simplest and best way to handle the problem if your object model allows it.
string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
})
This makes the serializer emit a $type="<typename>"
property that it can use to reconstruct the correct type. But I would warn against this, by default it includes the full namespace, to it makes renaming and moving types difficult, and it can result in security problems. System.Text.Json uses attributes to specify the type name, and that is an approach I much prefer.
You can use JsonTextReader to parse the json tree and do whatever you want with it. This allow for a high degree of flexibility, but is the most cumbersome to use.