使用改造的 JSON 解析
Posted
技术标签:
【中文标题】使用改造的 JSON 解析【英文标题】:JSON parsing using retrofit 【发布时间】:2014-07-16 21:19:24 【问题描述】:我有一个示例 JSON 文件,我想使用改造在 Java 中进行解析。我是改造新手,对 Java 也有点陌生。我在网上看到的例子不是 我现在清楚。有人可以解释我如何使用改造从以下 JSON 结构中提取 movie_logo 字段吗?
"url":"sample_url",
"movies_metadata":
"movies":
"Movie 1":
"Description":"Sample description for Movie 1",
"Movie_Logo":"logo1.png"
,
"Movie 2":
"Description":"Sample description for Movie 2",
"Movie_Logo":"logo1.png"
,
"Movie 3":
"Description":"Sample description for Movie 3",
"Movie_Logo":"logo1.png"
【问题讨论】:
如果您对 GSON 感兴趣,我可以为您提供一些样品。 见***.com/questions/23070298/… 【参考方案1】:Retrofit 并没有真正用于将 JSON 解析为 Java 对象(在内部它实际上使用 GSON 来解析 API 响应)。我建议使用JSON.org、GSON 或Jackson 来解析您的JSON 文件。最简单的方法是使用 JSON.org 解析器:
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
@Slf4j
public class JsonTest
@Test
public void test() throws Exception
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://jsonblob.com/api/jsonBlob/5384f843e4b0441b35d1329d");
request.addHeader("accept", "application/json");
HttpResponse response = client.execute(request);
String json = IOUtils.toString(response.getEntity().getContent());
//here's where you're actually parsing the JSON
JSONObject object = new JSONObject(json);
JSONObject metadata = object.getJSONObject("movies_metadata");
JSONObject movies = metadata.getJSONObject("movies");
JSONArray movieNames = movies.names();
for (int i = 1; i< movieNames.length(); i++)
String movieKey = movieNames.getString(i);
log.info("The current object's key is ", movieKey);
JSONObject movie = movies.getJSONObject(movieKey);
log.info("The Description is ", movie.getString("Description"));
log.info("The Movie_Logo is ", movie.getString("Movie_Logo"));
我将您的 JSON 放入 JSON Blob,然后使用他们的 API 在单元测试中请求它。单元测试的输出是:
14:49:30.450 [main] INFO JsonTest - The current object's key is Movie 2
14:49:30.452 [main] INFO JsonTest - The Description is Sample description for Movie 2
14:49:30.452 [main] INFO JsonTest - The Movie_Logo is logo1.png
14:49:30.452 [main] INFO JsonTest - The current object's key is Movie 1
14:49:30.453 [main] INFO JsonTest - The Description is Sample description for Movie 1
14:49:30.453 [main] INFO JsonTest - The Movie_Logo is logo1.png
【讨论】:
以上是关于使用改造的 JSON 解析的主要内容,如果未能解决你的问题,请参考以下文章