0

How to convert Json array to list of objects in c#

MY Json array:

    {"allAdultFares":["0-5000.00","1-8000.00"],"Flag":"N"},

Class:

   public List<Sellrate> allAdultFares { get; set; }



    public class Sellrate
    {
    public string Singe { get; set; }
     public string Double { get; set; }
     }

I need O/p:

Singe :5000

Double :8000

3
  • Can you show a few more lines of the json? Commented Oct 17, 2015 at 9:33
  • Well your class doesn't model your JSON at all, as far as I can see. I suggest you create a class that does model your JSON (e.g. with a List<string> property for allAdultFares, and a string property for Flag) and then convert that into your SellRate class later. Commented Oct 17, 2015 at 9:36
  • how to add list from array objects Commented Oct 17, 2015 at 9:44

3 Answers 3

1

Here's some simple code to parse your json without creating a proper class to represent its structure like Jon suggested. I might have misunderstood the exact structure of your json so here is the sample json I worked with, perhaps you will need to make small adjustments to it will fit your case:

{ 
  "rateDetails":[
    {
      "date":"19-9-2015",
      "allAdultFares":["0-5000.00","1-8000.00"],
      "Flag":"N"
    },
    {
      "date":"20-9-2015",
      "allAdultFares":["0-9000.00","1-9000.00"],
      "Flag":"N"
    }
  ]
}

I used JSon.Net to parse the file, you can get it from nuget.

        var input = JObject.Parse(File.ReadAllText("sample.json"));
        var rateDetails = (JArray)input["rateDetails"];
        var a = rateDetails
                    .Select(t => (JArray)t["allAdultFares"])
                    .Select(t => 
                        new Sellrate() 
                        { 
                          Singe = t[0].ToString().Split('-')[1].Replace(@"""", ""), 
                          Double = t[1].ToString().Split('-')[1].Replace(@"""", "") 
                        }).ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

i changed & getting o/p

       public string[] allAdultFares{ get; set; }

Comments

0
Single: { "field1":"value1","field2":"value2" }
Array: [ { "field1":"value1","field2":"value2" }, { "field1":"value1","field2":"value2" } ]


public class Test
{
  public string field1 { get; set; }
  public string field2 { get; set; } 
}  


Test myDeserializedObj = (Test)JavaScriptConvert.DeserializeObject(Request["jsonString"], typeof(Test));


List<test> myDeserializedObjList = (List<test>)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List<test>));

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.