Ali Foroughi
Ali Foroughi

Reputation: 4609

Parse a JSON string

I have a JSON string like following string

{
    FlightId : 1,
    [
        {
            AirplaneId : 1
        },
        {
            AirplaneId : 2
        }
    ]
}

I have defined 2 classes to convert this JSON string to the objects of these 2 classes :

class Airplane
{
    int AirplaneId;
}

class Flight
{
    int FlightId;
    List<Airplane> Airplanes;
}

During convert the string to these classes objects I get an error. The error tells me that JSON string is not recognized and I should define a name for the list in my JSON string. I can not change the JSON string , how to define my class to convert this JSON String

Upvotes: 1

Views: 83

Answers (2)

Omri Aharon
Omri Aharon

Reputation: 17064

Yes, you get an error since that is not a valid JSON.

In order to make it valid, you need to have a key to match your list value:

{
    "FlightId" : 1,
    "Airplanes": [
        {
            "AirplaneId" : 1
        },
        {
            "AirplaneId" : 2
        }
    ]
}

Also, you need to wrap your key values in quotes.

You can use https://www.jsoneditoronline.org/ in the future to make sure your JSON strings are valid.

Upvotes: 3

BendEg
BendEg

Reputation: 21088

The problem is your array, you need to define a key for it, like:

{
    "FlightId" : 1,
    "Airplanes": [
        {
            "AirplaneId" : 1
        },
        {
            "AirplaneId" : 2
        }
    ]
}

Airplanes must be a list in your class later.

JSON is a "Key-Value" based format, so every value (even arrays) needs a key.

Upvotes: 1

Related Questions