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.
2
Answers
I don’t see the reason that defines the
Message
property inRootobject1
as anobject
type as you know the data structure.The quick way to resolve this is to define
Message
withMessage1
type.Alternatively, you may look to convert the
JObject
to theMessage1
type.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 aMessage1
. Json will inspect theRootobject1
to figure out the various types it should use, but if you only haveobject
-property there is no type information to go on.There are a few solutions
Use the actual type
This is by far the simplest and best way to handle the problem if your object model allows it.
Specify type name handling
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.Parse the json by hand
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.