JsonConverter(typeof())无法处理以下json响应。 [英] JsonConverter(typeof()) is not working to handle following json response.
本文介绍了JsonConverter(typeof())无法处理以下json响应。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从API调用调用API和Response如下。当我使用 JsonConvert.DeserializeObject< class1>(resp)
因为不同调用的参数类型发生变化时,它会抛出异常。我使用 JsonConverter(typeof())
来处理类型转换。但它没有用。当json响应参数的类型发生变化时,如何处理?
I am calling API and Response from the API call is as follows. It throws Exception when I used JsonConvert.DeserializeObject<class1>(resp)
as because type of the parameters changes for different call. I have used JsonConverter(typeof())
to handle type conversion. But it is not working. How can i handle when type of the parameters of the json response changes?
public class class1
{
public double lat { get; set; }
public double @long { get; set; }
public int orra { get; set; }
public List<string> hotelPolicy { get; set; }
}
public class class1
{
public object lat { get; set; }
public object @long { get; set; }
public double orra { get; set; }
public List<object> hotelPolicy { get; set; }
}
推荐答案
我不认为这个问题有一个神奇的银弹。
我建议根据几个预定义模式之一验证传入的JSON数据。如果它针对特定模式进行验证,则可以安全地针对您的DTO类调用JsonConvert.DeserializeObject< T>()。
JSON模式验证 [ ^ ]
这种方法性能更高(避免了引发运行时异常的开销)<另一个更直接的方法就是创建一个'TryParse'样式函数,它可以吞下任何异常,并多次调用它,直到有效结果为止。返回...
I don't think there is a magic silver bullet for this issue.
I would suggest validating the incoming JSON data against one of several pre-defined schemas. If it validates against a particular schema, you can safely call JsonConvert.DeserializeObject<T>() against your DTO class.
JSON Schema Validation[^]
This approach as more performant (it avoids the overhead of raising runtime exceptions)
The other more straight-forward approach would just be to create a 'TryParse' style function, which swallows any exceptions, and call it multiple times, until a valid result is returned ...
public bool TryParseJson<T>(string json, out T value) where T: class, new()
{
value = new T();
bool result = false;
try{
value = JsonConvert.DeserializeObject<T>(json);
result = true;
}catch(Exception)
{
}
return result;
}
这篇关于JsonConverter(typeof())无法处理以下json响应。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文