0

I am trying to deserialize a JSON array in the format such as below

[
    {
        "Id": 111,
        "Name": "ABC"

    },
    {
        "Id": 222,
        "Name": "CDE"
    },
    {
        "Id": 333,
        "Name": "EFG"
    }
]

I Have the class

public class IDInformation
    {
        public List<IDInformation> ID{ get; set; }
    }

and I am trying to use it here where I am getting the Exception

Newtonsoft.Json.JsonSerializationException

var details= JsonConvert.DeserializeObject <IDInformation>(File);

I tried some of the fixes on some other SO questions as well but couldn't quite get what I wanted ..

What I am rying to do here is store all the ID in each of the separate JSON objects in a List (For example I want to iterate through this file and store 111,222,333 in a List )

Would really appreciate some help if anyone has come across something like this before.

1
  • Use json2csharp.com to generate classes for your JSON. You need a class with Id and Name property. Commented Nov 20, 2019 at 1:11

2 Answers 2

4

You need to have following class to be able to deserialize the JSON successfully.

public class IDInformation
{
     public int Id {get;set;}
     public string Name {get;set;}
}

Then you can deserialize your JSON to a collection of IDInformation as following.

var list = JsonConvert.DeserializeObject <List<IDInformation>>(File);

From the list you can further create collection of ID of all the objects in the list as following.

var idList = list.Select(x => x.Id).ToList();

This will give you collection of integer values populated by Id values from the JSON array.

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

1 Comment

Great ! Thanks for the help. Understood where my mistake was
0

The exception you're getting is because it cannot deserialize the json into your IDInformation class.

Change your IDInformation class to:

public class IDInformation
{
    public int Id { get; set; }
}

Then deserialize like so:

var details = JsonConvert.DeserializeObject<List<IDInformation>>(File);

Note how the field name Id matches the Json Id field.

2 Comments

Name is missing from your class though?
I might be mistaken but off the top of my head you do not need every json field in your class - so if you were not interested in Name you could just omit it from your class altogether.

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.