Search code examples
asp.netjsonserializationdeserializationdatacontractserializer

Deserialization using Datacontractserializer. Only the first object on the list is getting filled


I want to put the data I have in my Json file into the objects I have created, however it works only with the first part of the json file. In this case Batch.

I get all the data of Batch into my Batch object. However Crop, Sift and Parcel are empty.

What do I have to do to fill them?

Here is my class with objects.

[DataContract(Namespace="Importer")]
public class Importer
{

    [DataMember]
    public List<Crop> Crop { get; set; }

    [DataMember]
    public List<Batch> Batch {get; set;}

    [DataMember]
    public List<Sift> Sift { get; set; }

    [DataMember]
    public List<Parcel> Parcel { get; set; }

My Json file.

{
    "Batch": [
        { "iID": 4, "sDescription": "Afbroei" },
        { "iID": 5, "sDescription": "Hij" }
    ]

    "Crop": [
        { "iID": 15, "sDescription": "Bloem" },
        { "iID": 16, "sDescription": "Bloem 222" },
        { "iID": 17, "sDescription": "TEST" }
    ]


    "Sift": [
        { "iID": 5, "sDescription": "8-9", "iBolSize": 8 },
        { "iID": 6, "sDescription": "12-13", "iBolSize": 12 }
    ]

    "Parcel": [ 
        { "iID": 3, "sDescription": "Hexapole", "sPlace": "Beverwijk", "sAddress": "", "sZipCode": "", "sPhoneNumber": "", "sInfo": "", "sEmail": "", "bActive": 1 }
    ]


}

My Deserialization code.

 public static void ImportDeSerializer()
    {
 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Importer));

        MemoryStream stream1 = new MemoryStream();

        using (FileStream file = new FileStream("D:/Projects/Hexateelt/ASP.NET_Hexateelt/Website/Imports/jsonImport.json", FileMode.Open, FileAccess.Read))
        {

            file.CopyTo(stream1);
            stream1.Position = 0;
        }

        Importer import = (Importer)ser.ReadObject(stream1);
    }

Solution

  • Add comma after each property in JSON object:

    {
      "Batch": [
        { "iID": 4, "sDescription": "Afbroei" },
        { "iID": 5, "sDescription": "Hij" }
      ],
    
      "Crop": [
        { "iID": 15, "sDescription": "Bloem" },
        { "iID": 16, "sDescription": "Bloem 222" },
        { "iID": 17, "sDescription": "TEST" }
      ],
    
    
      "Sift": [
        { "iID": 5, "sDescription": "8-9", "iBolSize": 8 },
        { "iID": 6, "sDescription": "12-13", "iBolSize": 12 }
      ],
    
      "Parcel": [ 
        { "iID": 3, "sDescription": "Hexapole", "sPlace": "Beverwijk", "sAddress": "", "sZipCode": "", "sPhoneNumber": "", "sInfo": "", "sEmail": "", "bActive": 1 }
      ]
    }