我有像这样下面的json字符串
{"0":{"in":"mmm","loc":"1234"},"1":{"in":"mmm","loc":"1234"}}
现在我需要像
那样解析它们in | loc
---------
mmm| 1234
mmm| 1234
到目前为止我做了
public with sharing class Search
{
public String strTag {get;set;}
public String strlocation {get;set;}
public String result {get;set;}
public PageReference find() {
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://test.3spire.net/index.php?in='+strTag+'&loc='+strlocation);
req.setMethod('GET');
//these parts of the POST you may want to customize
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
try {
res = http.send(req);
} catch(System.CalloutException e) {
system.debug('Callout error: '+ e);
result = ''+e;
}
Result results = (Result) JSON.deserialize(res.getBody(),ResultSet.class);
result = res.getBody();
system.debug(res.getBody());
return null;
}
public class ResultSet{
public List<Result> resultSet;
}
public class Result
{
public String ins;
public String loc;
}
}
但它的回报
System.TypeException:从运行时类型Search.ResultSet到Search.Result的转换无效
我怎样才能解决这个问题
提前致谢
答案 0 :(得分:2)
您正在呼叫JSON.deserialize(res.getBody(),ResultSet.class)
。第二个参数ResultSet
是您希望结果的Apex对象类型。但是,您尝试将其转换为Result
类型。
要么
Result results = JSON.deserialize(res.getBody(), Result.class);
或
ResultSet results = JSON.deserialize(res.getBody(), ResultSet.class);
在您的情况下,基于JSON,您似乎想要第二个选项。但是,您的JSON与ResultSet类也不完全匹配。您的JSON是地图,而不是列表。此外,“in”和“ins”之间存在字段不匹配。这个JSON与ResultSet类相匹配:
{{"ins":"mmm","loc":"1234"},{"ins":"mmm","loc":"1234"}}