随机JSON解析

时间:2020-03-06 16:55:39

标签: c# json

我正在尝试解析从服务台系统返回的JSON的很长段,我无法对其进行修改。到目前为止,我一直在C#中使用JavaScriptSerializer().Deserialize<Ticket>(data)方法,但是遇到的问题是JSON的变化会重新出现。具体而言,某些属性似乎具有随机子属性。接下来是模糊数据的精简版本,说明了这一点:

{"ticket_id":"12345","custom_fields":[{"customgroup_id":"12","custom_group":[{"customfield_id":"33","custom_field_data":{"customfield_data_id":"12345"}},{"customfield_id":"34","custom_field_data":{"customfield_data_id":"12345"}},{"customfield_id":"35","custom_field_data":{"3":{"customfield_data_id":"12345"}}},{"customfield_id":"54","custom_field_data":{"customfield_data_id":"12345"}},{"customfield_id":"55","custom_field_data":{"6":{"customfield_data_id":"12345"}}}]}]}

Strange JSON

不相关的属性已被删除。如人们所见,有时custom_field_data紧跟着包含customfield_data_id的数组,但有时紧跟着一个完全随机的整数,而 then 紧跟着{{1 }}。我的问题是我不知道该如何解析-到目前为止,我只是将JSON与对应的类进行了映射,但是考虑到以下事实:无论这些整数是否会在{{之间, 1}}及其列表,我不知道如何解析它。

如果有一种方法可以保留我目前制作类映射的工作,那将是首选。如果唯一的解决方案是完全切换到其他库/方法,那就这样吧。谢谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

如果无法创建与JSON对象匹配100%的C#类。最好的选择是编写.NET CORE中支持的自己的自定义JSON转换器(System.Text.Json.Serialization.JsonConverter)。看看这个https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#support-polymorphic-deserialization

基本上,它允许您逐个逐步遍历每个JSON节点,并决定在何处解析该值(将其放入类的属性,字典或数组中)。

相关问题