简体   繁体   English

反序列化JSON不同的结构,但在C#中使用相同的名称

[英]Deserialize JSON different structure, but the same name in C#

I am working, in C#, with some API and it returns "Errors" in JSON with 404 and 200(!) status code, but with different structures. 我正在C#中使用某些API进行工作,并且它以404和200(!)状态代码在JSON中返回“错误”,但结构不同。

1) HTTP Status 200: 1)HTTP状态200:

{ "Errors": "Duplicated" }

2) HTTP Status 200: 2)HTTP状态200:

{ "Errors": {"some_key":"Invalid"} }

3) HTTP Status 404: 3)HTTP状态404:

{ "Errors": "some_key1":["Invalid"], "some_key2":["Invalid"] }

1 - Maps to String - OK, but not to Dictionary<string,string> 2 - Maps to Dictionary<string,string> , but not to string 3 - Maps it to ModelState Dictionary<string,List<string>> OK, as the StatusCode is diff (I rename "Errors" in Json string and map it to diff property name. 1-映射到String-确定,但不映射到Dictionary<string,string> 2-映射到Dictionary<string,string> ,但是不映射到字符串3-映射到ModelState Dictionary<string,List<string>>确定,如下StatusCode为diff(我在Json字符串中重命名“ Errors”,并将其映射到diff属性名称。

The only issue is with case 1 and 2 as both are returned with the same HTTP Status code and the same node name "Errors". 唯一的问题是情况1和2,因为它们都返回了相同的HTTP状态代码和相同的节点名称“错误”。

Have anybody worked with these cases? 有人处理过这些案件吗? How do you handle them? 您如何处理它们? Is there any Netwon Json deserialzier setting to flatten Case 2 to just string or Case 1 into dictionary with 1,2,3.. autgenerated keys? 是否有任何Netwon Json deserialzier设置可以将Case 2压平为仅字符串或Case 1到具有1,2,3 ..自动生成键的字典中?

Any other idea? 还有其他想法吗?

Cheers 干杯

Make your property a dynamic object. 使您的属性成为动态对象。 https://msdn.microsoft.com/en-us/library/dd264736.aspx . https://msdn.microsoft.com/zh-CN/library/dd264736.aspx Then based on what properties are available you can convert it or can read the properties directly off the dynamic. 然后,根据可用的属性,可以对其进行转换,也可以直接从动态读取属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM