How can I parse a JSON string that would cause illegal C# identifiers?

后端 未结 3 2284
孤城傲影
孤城傲影 2020-11-21 05:24

I have been using NewtonSoft JSON Convert library to parse and convert JSON string to C# objects. But now I have came across a really awkward JSON string and I am unable to

相关标签:
3条回答
  • 2020-11-21 05:32

    While the dictionary is the best solution for the specific case you had, the question you asked could also be interpreted as:

    how do I deserialize objects with property names that cannot be used in C#?

    For example what if you had

    {
        "0": "04:15",
        "zzz": "foo"
    }
    

    Solution: use annotations:

    public class Item
    {
       [JsonProperty("0")]
       public string AnyName { get; set; }
    
       [JsonProperty("zzz")]
       public string AnotherName { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-21 05:41

    You can use this extensions:

    public static class JsonExtensions
    {
        public static Dictionary<string, T> ToObject<T>(this string json)
        {
            return JsonConvert.DeserializeObject<Dictionary<string, T>>(json);
        }
    
        public static string ToJson<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:54

    You can deserialize to a dictionary.

    public class Item
    {
        public string fajr { get; set; }
        public string sunrise { get; set; }
        public string zuhr { get; set; }
        public string asr { get; set; }
        public string maghrib { get; set; }
        public string isha { get; set; }
    }
    

    var dict = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
    
    0 讨论(0)
提交回复
热议问题