0

The problem is I have different types of objects (It know how to handle this with one type): Something like this:

{"myObjects": [
        {
            "Type":"sampleType1",
            "Name":"sampleName1",
            "Size":"sampleSize1"
        },
        {
            "Type":"sampleType2",
            "Name":"sampleName2",
            "Size":"sampleSize2"
        }
    ]
}

I handle with just:

JsonConvert.DeserializeObject<MyObjectContainer>(json);

where MyObjectContainer has a property:

public List<MyObjects> myObjects { get; set; }

The problem comes when I get an object with optional parameters:

{"myObjects": [
        {
            "Type":"sampleType1",
            "Name":"sampleName1",
            "Size":"sampleSize1"
        },
        {
            "Type":"sampleType2",
            "Name":"sampleName2",
            "Size":"sampleSize2",
            "AdditionalInfo":"AdditionalInfo" 
        }
    ]
}

To serialize it will be easy I think. I'll just create class AdditionalInfoObject : MyObject with property string AdditionalInfo.

But how to deserialize such json into my List?

2 Answers2

0

You can tell the JSON Serializer to ignore the property, if its null. But mind that this will just ignore every Property that's null. So if it was initialized with a default value other than that, this won't work.

Here's an exmaple: How to ignore a property in class if null, using json.net

chrsi
  • 992
  • 9
  • 24
  • Could you give me another tip how to aproach it? I just cannot see how I can deserialize the second json in my example into some datacontainer containing two different object types (Myobject, AdditionalInfoObject) – cantdoanything33 Jul 28 '17 at 07:40
0

You can try below code. As per your JSON format, I have created class for desalinization:

public class myObjects
{
    public string Type { get; set; }
    public string Name { get; set; }
    public string Size { get; set; }
    public string AdditionalInfo { get; set; }
}

public class objMain
{
    public List<myObjects> myObjects { get; set; }
}

Then you can call deserialization method.

Note:- If AdditionalInfo property found in your JSON then it will give you value for this, else it will be null. No need for extra care.

var jsonData = "{ 'myObjects': [{'Type':'sampleType1','Name':'sampleName1','Size':'sampleSize1'},{'Type':'sampleType2','Name':'sampleName2','Size':'sampleSize2'}]}";
string jsonData1 = "{ 'myObjects': [{'Type':'sampleType1','Name':'sampleName1','Size':'sampleSize1'},{'Type':'sampleType2','Name':'sampleName2','Size':'sampleSize2','AdditionalInfo':'AdditionalInfo' }]}";

objMain myNames = JsonConvert.DeserializeObject<objMain>(jsonData);
objMain myNames1 = JsonConvert.DeserializeObject<objMain>(jsonData1); 
T.S.
  • 18,195
  • 11
  • 58
  • 78
Bharat
  • 2,441
  • 3
  • 24
  • 36