c# Deserialize unlabelled JSON array

后端 未结 1 674
太阳男子
太阳男子 2021-01-28 05:56

I am attempting to deserialize a piece of JSON with a specific structure like so:

{  
    \"label1\": \"value1\",  
    \"label2\": [  
        [  
            [         


        
相关标签:
1条回答
  • 2021-01-28 06:08

    You can use the custom JsonConverter ObjectToArrayConverter<Full_Result> from this answer to C# JSON.NET - Deserialize response that uses an unusual data structure to deserialize your JSON into your existing typed data model. Modify Full_Result as follows:

    [JsonConverter(typeof(ObjectToArrayConverter<Full_Result>))]
    public class Full_Result 
    {
        [JsonProperty(Order = 1)]
        public IList<string> values { get; set; }
        [JsonProperty(Order = 2)]
        public float score { get; set; }
    }
    

    And you will now be able to deserialize as follows:

    Parsed_JSON result = JsonConvert.DeserializeObject<Parsed_JSON>(JSON);
    

    Notes:

    • ObjectToArrayConverter<T> works by mapping the serializable members of T to an array, where the array sequence is defined by the value of the JsonPropertyAttribute.Order attribute applied to each member. Data contract attributes with DataMemberAttribute.Order set could be used instead, if you prefer.

    • In your JSON the "score" values are not actually numbers:

      score_1
      score_2
      

      I am assuming that this is a typo in the question and that these values are in fact well-formed numbers as defined by the JSON standard.

    Sample fiddle here.

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