Deserializing JSON and access to elements

后端 未结 2 1768
心在旅途
心在旅途 2021-01-29 14:55

I have the following code :

dynamic stuff = JsonConvert.DeserializeObject(\"{ \'Name\': \'Jon Smith\', \'Address\': [\'A\', \'B\', \'C\'], \'Age\': 42 }\");
var          


        
相关标签:
2条回答
  • 2021-01-29 15:08

    This is a simple solution which will help you also in a lot of Projects.

    {
      "Name": "Jon Smith",
      "Address": 
      [
        "A",
        "B",
        "C"
      ],
      "Age": "42"
    }
    

    You have to create a class for your items.

    public class JSONClass
    {
       public string Name { get; set; }
       public string[] Address { get; set; }
       public string Age { get; set; }
    }
    

    Then you have to make a List that will keep your items:

    public class ItemsList
    {
       public List<JSONClass> JsonItems { get; set;}  
    }
    
    

    And then you can simple retrieve your Items.

    ItemsList itemsList = new ItemsList();
    
    itemsList.JsonItems = JsonConvert.DeserializeObject<ItemsList>("yourAPIResponse").JsonItems ;
    
    0 讨论(0)
  • 2021-01-29 15:22

    You can use the same approach with Name property, then iterate the Address value, since it's an array

    var address = stuff.Address;
    foreach (var item in address)
    {
        Console.WriteLine(item);
    }
    
    0 讨论(0)
提交回复
热议问题