Java JSON的反序列化,不匹配
我的SpringMVC项目遇到了麻烦,它涉及到使用API来获取营养事实。我继续得到一个嵌套异常是java.lang.IllegalArgumentException:参数类型不匹配。下面是我为反序列化过程创建的JSON响应和类Java JSON的反序列化,不匹配,java,json,spring,spring-mvc,deserialization,Java,Json,Spring,Spring Mvc,Deserialization,我的SpringMVC项目遇到了麻烦,它涉及到使用API来获取营养事实。我继续得到一个嵌套异常是java.lang.IllegalArgumentException:参数类型不匹配。下面是我为反序列化过程创建的JSON响应和类 public FullResponse search() throws ClientProtocolException, IOException{ CloseableHttpClient client = HttpClients.createDefault();
public FullResponse search() throws ClientProtocolException, IOException{
CloseableHttpClient client = HttpClients.createDefault();
HttpGet getProducts = new HttpGet("https://api.nutritionix.com/v1_1/search/"+ value +"?results=0%3A6&cal_min=0&cal_max=50000&fields=item_name%2Citem_id&appId=ac23ceb3&appKey=API_KEY");
CloseableHttpResponse productResponse = client.execute(getProducts);
String entityString = EntityUtils.toString(productResponse.getEntity());
FullResponse test = new JSONDeserializer<FullResponse> ().deserialize(entityString,FullResponse.class);
return test;
}
任何关于出了什么问题的想法都会大有帮助
下面是来自请求的JSON
{
"total_hits":11025,
"max_score":11.122117,
"hits":[{
"_index":"nixproductionv13",
"_type":"item",
"_id":"513fceb375b8dbbc210000e4",
"_score":11.122117,
"fields":{"item_name":"Whole Milk - 1 tbsp"}},
{"_index":"nixproductionv13",
"_type":"item",
"_id":"513fceb375b8dbbc2100017b",
"_score":10.7038355,
"fields":{"item_name":"2% Milk - 1 cup"}},
{"_index":"nixproductionv13",
"_type":"item",
"_id":"513fceb375b8dbbc210000f3",
"_score":10.7038355,
"fields":{"item_name":"1% Milk - 1 cup"}},
{"_index":"nixproductionv13",
"_type":"item",
"_id":"513fceb375b8dbbc210000fb",
"_score":10.689078,
"fields":{"item_name":"Skim Milk - 1 cup"}},
{"_index":"nixproductionv13",
"_type":"item",
"_id":"513fceb375b8dbbc210000e3",
"_score":10.65872,
"fields":{"item_name":"Whole Milk - 1 fl oz"}},
{"_index":"nixproductionv13",
"_type":"item",
"_id":"513fceb375b8dbbc2100017a",
"_score":10.392,
"fields":{"item_name":"2% Milk - 1 quart"}}]}
我不太清楚
flexjson
,但它似乎不喜欢从JSON数字字段转换为JavaString
字段。例如,当尝试反序列化此JSON编号时,会发生此错误
"_score":10.7038355
进入这个Java字符串
字段
String _score;
如果将所有具有相应JSON数字字段的字符串
字段更改为Double类型的字段,则代码将正常工作
还要注意,字段
JSON对象
"fields":{"item_name":"Whole Milk - 1 tbsp"}},
是JSON对象,而不是JSON数组。因此,你需要改变
List<Fields> fields;
并适当地更改getter和setter
或者,您可以使用不同的JSON解析库,如Gson,它支持这些标准类型转换。请发布完整的堆栈跟踪,了解为什么它仍然反序列化并导致空产品名?@user3080107是的,您应该使用与字段名匹配的常规getter和setter名称。例如,setItem\u name
和getItem\u name
。还请注意,Java命名约定不建议在变量名中使用。
。查看许多库使用的名称。命名背后的原因是因为JSON响应提供了这些名称,我认为我已经使用了这些名称,否则它将无法序列化JSONresponse@user3080107每个框架都有不同的规则。有些直接使用字段名的反射。其他人使用setter。其他人则同时使用这两种注释,甚至是注释。每个人都非常乐于助人。我非常感谢这样一个网站,我只是希望我不会花这么长时间才意识到这个网站的存在。
String _score;
"fields":{"item_name":"Whole Milk - 1 tbsp"}},
List<Fields> fields;
Fields fields;