0

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

2
  • 3
    btw: that isn't valid JSON; the names should be in quotes; it also isn't valid C# Commented Mar 16, 2018 at 15:36
  • @MarcGravell Thanks, I do understand that, I was just trying to give an idea of my problem, not pasting actual code which has too much going on Commented Mar 16, 2018 at 15:44

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.