Deserializing multiple JSON-arrays of different ty

2020-07-29 05:08发布

问题:

I have a JSON-string with a fixed number of arrays of different objects (created in Java with JSONObjects and JSONArrays):

[
  [ //The first type of object
    {
      "Initials":"MUS"
    },
    {
      "Initials":"NA"
    }
  ],
  [ //The second type
    {
      "ToolId":17
    },
    {
      ...
    }
  ]
  ... //etc.
]

So I've created some Dummy-classes that has corresponding properties to the objects within the array, which works:

private class DummyEmployee
{
    public string Initials { get; set; }
}
//etc.

But I can't figure out how the container class should be designed. This is how I did it:

private class DataContainer
{
    public List<DummyEmployee> Employees { get; set; }
    public List<DummySecondType> SecondTypes { get; set; }
    //etc.
}

This is how I attempt to deserialize the JSON-data:

JavaScriptSerializer ser = new JavaScriptSerializer();

string jsonDataFromClient = ...;

DataContainer jsonData = ser.Deserialize<DataContainer>(jsonDataFromClient);

And it doesn't work. I get the following error while passing the data: Type 'GUI.ValidateLoginData+DataContainer' is not supported for deserialization of an array.

I couldn't find any other subjects on the matter of deserializing arrays of different objects.

回答1:

yes i will not work
notice that in your javascript object is basically an array and because javascript is a dynamic language there it is a valid array
where as c# isnt so an array(or list) must contain objects of same kind. however if you still need to implement this and you have control over your JSON structure edit it to this

{
  Employees:[ //The first type of object
    {
      "Initials":"MUS"
    },
    {
      "Initials":"NA"
    }
  ],
  SecondTypes:[ //The second type
    {
      "ToolId":17
    },
    {
      ...
    }
  ]
  ... //etc.
}

and your current c# object might map correctly.

and if you dont have control over the JSON structure then you have to use dynamic objects in c#
UPDATE:-for the case in which you dont have control over your JSON structure (or you dont wanna edit it).
try deserializing your JSON object to an array of dynamic type
UPDATE 2:- because you are curious try deserializing the existing JSON structure to an object of type List<List<dynamic>> and though i havent tried it but it should work fine.
one disadvantage of this solution however is that you wont be able to distinguish between two different types of objects namely Employee and SecondTypes



回答2:

Use this online tool to create the C# classes for you. You can then fine tune the classes (Name, etc) as per you need. At least, you can get idea that the model classes that you are creating are correct or not.

JSON to C#



回答3:

did you add [Serializable] attribute to your DataContainer?