0

This is my json file

{
  "UseCase1": {
    "UseCaseId": "Usecase1",
    "UseCaseDescription": "description1"

},
"UseCase2": {
    "UseCaseId": "Usecase2",
    "UseCaseDescription": "description2"

}

}

This is my class

public class UseCase
    {
        public string UseCaseId { get; set;}
        public string UseCaseDescription { get; set;}
    }

How to assign the json elements to a list of this class(UseCase)

I tried the below code, but it is not working

string Json = System.IO.File.ReadAllText(@"D:\ENERGY METER\ENERGY METER –IRP\SourceCode\EDMI.EnergyMeterPOC\EDMI.EnergyMeterPOC.Repository\DataSource\UseCaseData.json");
            JavaScriptSerializer ser = new JavaScriptSerializer();
            var personlist = ser.Deserialize<List<UseCase>>(Json);
            return personlist;
3

1 Answer 1

0

You need to look at your Json again.

When placed into a tool like JSON Utils, you end up with the following.

public class UseCase1
{
    public string UseCaseId { get; set; }
    public string UseCaseDescription { get; set; }
}

public class UseCase2
{
    public string UseCaseId { get; set; }
    public string UseCaseDescription { get; set; }
}

public class RootObject
{
    public UseCase1 UseCase1 { get; set; }
    public UseCase2 UseCase2 { get; set; }
}

In order for your object to be in a list it woudl first have to be an array which your file is not.

You Json file would have to be looking like this to satisfy your UseCase collection requirement

{
  "UseCases": [
  {
    "UseCaseId": "Usecase1",
    "UseCaseDescription": "description1"
  },
  {
    "UseCaseId": "Usecase2",
    "UseCaseDescription": "description2"
  }]
}

which would have the following classes when deserialized...

public class UseCase
{
    public string UseCaseId { get; set; }
    public string UseCaseDescription { get; set; }
}

public class RootObject
{
    public List<UseCase> UseCases { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.