use*_*130 19 java android json unirest mashape
我正在使用Unirest库从Mashape API中检索JSON.我使用以下代码进行调用:
HttpResponse<JsonNode> request = Unirest.get(URL)
.header("X-Mashape-Authorization", MASHAPE_AUTH)
.asJson();
Run Code Online (Sandbox Code Playgroud)
这将以HttpResponse<JsonNode>
我不熟悉的形式返回我的JSON .
从阅读有限的文档,似乎我必须调用getBody()
响应对象,以获得一个JsonNode对象.我仍然不知道如何处理JsonNode对象.
开始解析这些数据的最佳方法是什么?
编辑: 如果它有助于提供示例,我想要解析的JSON看起来像这样:
{
"success": "1",
"error_number": "",
"error_message": "",
"results": [
{
"name": "name1",
"formatedName": "Name 1"
},
{
"name": "testtesttest",
"formatedName": "Test Test Test"
},
{
"name": "nametest2",
"formatedName": "Name Test 2"
},
{
"name": "nametest3",
"formatedName": "Name Test 3"
}
]
}
Run Code Online (Sandbox Code Playgroud)
l8n*_*ite 23
试图今天为自己解决这个问题.源代码可能是您将获得的唯一文档.这是tl;博士
// the request from your question
HttpResponse<JsonNode> request = Unirest.get(URL)
.header("X-Mashape-Authorization", MASHAPE_AUTH)
.asJson();
// retrieve the parsed JSONObject from the response
JSONObject myObj = request.getBody().getObject();
// extract fields from the object
String msg = myObj.getString("error_message");
JSONArray results = myObj.getJSONArray();
Run Code Online (Sandbox Code Playgroud)
以下是我所做的洞察的更多解释:
从HttpResponse类我们可以看到它将getBody()
返回实例变量body
,该变量在第92行被分配为:
this.body = (T) new JsonNode(jsonString)
Run Code Online (Sandbox Code Playgroud)
那么我们需要查看JsonNode类.构造函数接受一个表示要解析的JSON的字符串,并尝试创建a JSONObject
或a JSONArray
.幸运的org.json
是,这些对象来自于文档.
由于响应可以轻松检索为字符串,因此如果您不想手动遍历 JSON,可以使用您想要的任何 JSON 库进行反序列化。我个人偏爱 Google 的 GSON,它能够轻松地将您的 JSON 响应映射到您创建的匹配对象。
HttpRequest request = Unirest.get(/*your request URI*/)
.headers(/*if needed*/)
.queryString(/*if needed*/);
HttpResponse<JsonNode> jsonResponse = request.asJson();
Gson gson = new Gson();
String responseJSONString = jsonResponse.getBody().toString();
MyResponseObject myObject = gson.fromJson(responseJSONString, String.class);
Run Code Online (Sandbox Code Playgroud)
在 JSON 字符串中,有两个符号可以指导您完成解析:
{ - 表示 JSONObject
[ - 表示 JSONArray
解析 json 字符串时,您应该迭代地遍历这些项目。要了解字符串中有多少个 JsonObjects 和 JsonArrays,以及应该从哪些开始解析,请使用像此网站这样的json-visualizer 工具。例如,对于您的字符串,结构如下:
如您所见,根对象是一个 JSONObject,它由一个带有三个 jsonOnject 的 JSONArray 组成。要解析这样的结构,您可以使用:
JSONObject jsonobj = new JSONObject(jsonstring);
String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");
String error_message = jsonObject.getString("error_message");
JSON Array jsonarray = jsonobj.getJSONArray();
String[] names = new String[jsonArray.length()];
String[] formattedNames = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
names [i] = jsonObject.getString("name");
formattedNames [i] = jsonObject.getString("formattedName");
}
Run Code Online (Sandbox Code Playgroud)
Unirest 中有一个序列化功能(可能是在 2015 年和 2014 年的答案之后出现的)。在当前版本 1.4.9 中,您可以使用方便的 asObject(Class) 和 body(Object) 方法。以下是反序列化 AWS CloudSearch 响应的示例。
import java.util.Arrays;
import org.apache.http.HttpStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public class UnirestExample {
public class Item {
private String full4kurl;
private String previewurl;
private String description;
@Override
public String toString() {
return "{full4kurl:" + full4kurl + ", previewurl:" + previewurl
+ ", description:" + description + "}";
}
}
public class Hit {
private String id;
private Item fields;
@Override
public String toString() {
return "{id:" + id + ", fields:" + fields + "}";
}
}
public class Hits {
private int found;
private int start;
private Hit[] hit;
@Override
public String toString() {
return "{found:" + found + ", start:" + start + ", hit:"
+ Arrays.toString(hit) + "}";
}
}
public class CloudSearchResult {
private Hits hits;
@Override
public String toString() {
return "{hits:" + hits + "}";
}
}
public static final String END_POINT = "AWS CloudSearch URL";
static {
Unirest.setTimeouts(1000, 5000);
Unirest.setObjectMapper(new ObjectMapper() {
private Gson gson = new GsonBuilder().disableHtmlEscaping()
.create();
@Override
public <T> T readValue(String value, Class<T> valueType) {
return gson.fromJson(value, valueType);
}
@Override
public String writeValue(Object value) {
return gson.toJson(value);
}
});
}
public static void main(String[] args) throws UnirestException {
HttpResponse<CloudSearchResult> response = Unirest.post(END_POINT)
.header("Header", "header").body("body")
.asObject(CloudSearchResult.class);
if (response.getStatus() == HttpStatus.SC_OK) {
CloudSearchResult body = response.getBody();
System.out.println(body);
} else {
throw new RuntimeException("Fail to invoke URL ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41399 次 |
最近记录: |