Parsing JSONObject

2019-05-30 07:43发布

I am trying to GET JSON From a webservice , which i was able to figure out . BTW This was my JSON Data -

   {
    "X-YZ-111/AB.CD": {
        "P1": "F",
        "P2": "43.46"
    },        

    "X-YZ-112/AB.CD": {
        "P1": "F",
        "P2": "8.02"
    },
    "X-YZ-113/AB.CD": {
        "P1": "F",
        "P2": "9066.58"
    },
    "X-YZ-114/AB.CD": {
        "P1": "F",
        "P2": "6.00"
    },
    "X-YZ-115/AB.CD": {
        "P1": "F",
        "P2": "6.00"
    },        
    "X-YZ-116/AB.CD": {
        "P1": "F",
        "P2": "10.00"
    }}


Using Windows.Data.Json;

private async void getJSON_click(object sender,RoutedEventArgs e)

{ 
   var client=new HttpClient();
   client.MaxResponseBufferSize=1024*1024;
   var response= await Client.GetAsync(new Uri(The URL here));
   var result = await response.Content.ReadAsStringAsync();

   var component=JsonObject.Parse(result);

}

Now i am able trying to parse it into a collection,where each item has "X-YZ-111/AB.CD" as name property and P1 and P2 as other 2 properties ,which i will try to bind to a Tile in UI using CollectionViewSource later.

Now This is the C# classes Json2CShardpDotCom is generating

public class Name
{
    public string Type { get; set; }
    public string Val { get; set; }
}

public class Root 
{
    public Name Name { get; set; }
}

Any suggestions on how to loop through these values using foreach and what classes i should make in C#?

Edit 1: BTW i know there has to be an dictionary where i first do a foreach on outer loop to retrieve the Name and foreach on inner loop to retrieve the P1 and P2.

But i am confused regarding what classes i should use in C# to consume JSON and create collection item out of my JSON

1条回答
Root(大扎)
2楼-- · 2019-05-30 08:35

i am confused regarding what classes i should use in C# to consume JSON and create collection item out of my JSON

You don't need any class. Just a little bit Linq

I would use Json.Net for this

var jObj = JObject.Parse(result);
var dict = jObj.Children()
           .Cast<JProperty>()
           .ToDictionary(p => p.Name, 
                         p => new Tuple<string, string>((string)p.Value["P1"], (string)p.Value["P2"]));

That is all. Sample usage would be:


foreach (var kv in dict)
{
    Console.WriteLine("{0}: {1} {2}", kv.Key, kv.Value.Item1, kv.Value.Item2);
}

EDIT

Same code using JsonObject

var jObj = JsonObject.Parse(json);
var dict = jObj.Cast<KeyValuePair<string, JsonValue>>()
           .ToDictionary(j=>j.Key,
                         j=>new Tuple<string,string>(j.Value["P1"],j.Value["P2"]));
查看更多
登录 后发表回答