My Json is
{
Id: 1,
Name:'Alex',
ConnectedObjectName:'Obj',
ConnectedObjectId: 99
}
I want this JSON to be converted to the following object
Class Response
{
int Id,
string Name,
ConnectedObject Obj
}
Class ConnectedObject
{
string COName,
int COId
}
Is there a way to achieve this using DataContractJsonSerializer
Most serializers want the object and the data to share a layout - so most json serializers would want ConnectedObjectName
and ConnectedObjectId
to exist on the root object, not an inner object. Usually, if the data isn't a good "fit" for what you want to map it into, the best approach is to use a separate DTO model that matches the data and the serializer, then map from the DTO model to the actual model you want programatically, or using a tool like auto-mapper.
If you used the DTO approach, just about any JSON deserializer would be fine here. Json.NET
is a good default. DataContractJsonSerializer would be way way down on my list of JSONserializers to consider.
To expand on what Marc Gravell has said, most JSON serializers would expect your JSON to look like the following, which would map correctly to your classes:
{
"Id": 1,
"Name": "Alex",
"Obj" : {
"COName": "Obj",
"COId": 99
}
}
The way to get around this would be to read your JSON into an object that matches it, and then map it form that object to the object that you want:
Deserialize to this object:
class COJson {
public int Id;
public string Name;
public string ConnectedObjectName;
public int ConnectedObjectId;
}
Then map to this object:
class Response {
public int Id;
public string Name;
public ConnectedObject Obj;
}
class ConnectedObject {
public string COName;
public string COId;
}
Like this:
using(var stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(COJson));
var jsonDto = (COJson)ser.ReadObject(stream);
var dto = new Response(){
Id = jsonDto.Id,
Name = jsonDto.Name,
Obj = new ConnectedObject(){
COName = jsonDto.ConnectedObjectName,
COId = jsonDto.ConnectedObjectId
}
};
return dto;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.