1

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

2
  • 2
    Could you edit your question to show us the code you're using to deserialize the JSON string, along with the precise error message? Commented Feb 24, 2015 at 13:11
  • 4
    "I have a JSON string like following..." No, you don't. You have something that looks like JSON, but isn't. Thus, you cannot use a JSON deserializer to parse it. Commented Feb 24, 2015 at 13:15

2 Answers 2

3

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.

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

3 Comments

I talk to my JSON String provider service and they believe they gave me a standard JSON string. What do you think ?!
@AliForoughi I think either they are wrong and they don't know what JSON is, or that you pasted a non string by accident (ordered descending by likelihood).
@AliForoughi if you are sure, you don't make any copy paste errors, send them a JSON specification. That's all
1

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.

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.