Access JSON fields with numeric keys

后端 未结 2 1119
无人及你
无人及你 2021-01-26 09:54

I want to access some address of pictures in a JSON, but the field name is a number and in c# a number is not a valid name for a variable...

My JSON:

{
         


        
相关标签:
2条回答
  • 2021-01-26 10:49

    You have to create Model object with properties, as in found json you're expecting.

    Then, for number properties, you can use JsonProperty attribute to name the property as number, for example:

    class MyModel {
       [JsonProperty("2")]
       public string Two {get; set;}
    }
    

    and then use DeserializeObject<MyModel> version

    This is simplified example, for your object you have to maintain the hierarchy and probably have another class for 'address' property and use it as property type in the main model.

    0 讨论(0)
  • 2021-01-26 10:52

    If you're able to modify the JSON, that's your best bet. What you have seems like it should be in an array:

    {
        "id":3441,
        "name":"test",
        "address":[
            "url.com\/45.jpg",
            "url.com\/23.jpg",
            "url.com\/65.jpg",
            "url.com\/789.jpg"
        ],
        "count":2
    }
    

    From there, your address is a simple array of strings, rather than a numbered key-value pair collection.

    0 讨论(0)
提交回复
热议问题