【问题标题】:Java extract from nested JSON从嵌套 JSON 中提取 Java
【发布时间】:2015-05-23 09:08:32
【问题描述】:

我想在我的程序中使用来自 yahoo 的财务数据,它已经可以了。我得到了完整的 JSON 内容,我可以显示它。但现在我想提取价格为int

public class Main {
public static void main (String[]args) throws IOException {


String sURL = "http://finance.yahoo.com/webservice/v1/symbols/googl/quote?format=json"; //just a string

// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();

// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.

    System.out.print(rootobj);

}
}

编辑 这是来自 yahoo 的 JSON 数据

{
"list" : { 
"meta" : { 
"type" : "resource-list",
"start" : 0,
"count" : 1
},
"resources" : [ 
{
"resource" : { 
"classname" : "Quote",
"fields" : { 
"name" : "Google Inc.",
"price" : "554.520020",
"symbol" : "GOOGL",
"ts" : "1432324800",
"type" : "equity",
"utctime" : "2015-05-22T20:00:00+0000",
"volume" : "1213288"
}
}
}

]
}
}

编辑 2

我更改了我的代码

   JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
        JsonObject obj = root.getAsJsonObject();
        JsonObject result = obj.get("list").getAsJsonObject();
        String result2 = result.get("resources").toString();


       System.out.print(result2);

现在我已经得到了这个

[{"resource":{"classname":"Quote","fields":{"name":"Google Inc.","price":"554.520020","symbol":"GOOGL","ts":"1432324800","type":"equity","utctime":"2015-05-22T20:00:00+0000","volume":"1213288"}}}]

我现在如何获得“价格”?

编辑 3

好的,我现在知道了,它有效,我只得到双倍的价格,但这是解决此任务的明智方法吗?

// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
    JsonObject obj = root.getAsJsonObject();
    JsonObject result = obj.get("list").getAsJsonObject();
    JsonArray result2 = result.get("resources").getAsJsonArray();
    JsonObject result3 = result2.get(0).getAsJsonObject();
    JsonObject result4 = result3.get("resource").getAsJsonObject();
    JsonObject result5 = result4.get("fields").getAsJsonObject();

    String result6 = result5.get("price").toString();
    result6 = result6.replace("\"", "");
    double value = Double.parseDouble(result6);


   System.out.print(value);

【问题讨论】:

  • 不清楚你在问什么。你到底想分裂什么?你能举个清楚的例子吗?
  • 我想拆分 JSON 数据以获取价格为 int 值。
  • 也许您的意思是提取数据(不拆分)?
  • 您是否考虑过使用 Json 解析器,例如 Gson?

标签: java json extract


【解决方案1】:

您应该到达“字段”对象以提取“名称”、“价格”等。 org.json 库易于使用。下面的示例代码:您作为字符串的响应:

    JSONObject obj1 = new JSONObject(response);
    JSONArray arr = obj1.getJSONObject("list").getJSONArray("resources"); //GETS RESOURCES ARRAY

    for (int i = 0; i < arr.length(); i++)
    {
        String resource = arr.getJSONObject(i).toString();
        JSONObject obj2 = new JSONObject(resource);

        String resourceObject = obj2.getJSONObject("resource").toString(); //RESOURCE OBJECT
        JSONObject obj3 = new JSONObject(resourceObject);


        String name = obj3.getJSONObject("fields").getString("name"); //REACHED THE FIELDS
        float price = (float)obj3.getJSONObject("fields").getDouble("price");

    System.out.println(name);  
    System.out.println(price);


    }

下载:http://mvnrepository.com/artifact/org.json/json

【讨论】:

  • 请检查我的 EDIT 2。
【解决方案2】:

他已经在使用 gson。

如果你想继续使用 gson 并且知道之前的结构,你可以创建存储数据的类。

class GoogleRequest{
    private GoogleList list;

    public GoogleList getList() {
        return list;
    }

    public void setList(GoogleList list) {
        this.list = list;
    }
}
// class for list
class GoogleList{
    private Meta meta;
    private List<Resources> resources;

    public List<Resources> getResources() {
        return resources;
    }

    public void setResources(List<Resources> resources) {
        this.resources = resources;
    }

    public Meta getMeta() {
        return meta;
    }

    public void setMeta(Meta meta) {
        this.meta = meta;
    }
}
// create other classes here like the Resources class
JsonParser jp = new JsonParser(); // from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream)request.getContent()));

GoogleRequest list = new Gson().fromJson(root,GoogleRequest.class);

GoogleRequest 应该包含一个 List 对象和一个 Meta 对象。 gson 将自省并设置属性。如果没有自省,gson 会将属性设置为 null。所以你可以使用。

if( list.getResources() != null ){
  // list is here
}else{
  // do some other code and parse diffrent json
}

如果您不知道它是数组还是对象,请创建不同的类来为您处理它。只需用 new Gson().fromJson() 解析数据;

现在请记住,您需要适合该工作的属性。假设你在 java 中有这个 json

 String json = "{\"price\" : \"554.520020\"}";

那么价格需要是 Double 或 double。如果你使用 Double 你可以检查

if( obj.getPrice() != null ){
  System.out.println( obj.getPrice().intValue() );
}

注意:如果将 double 转换为 int,则会失去精度

【讨论】:

  • 请检查我的 EDIT 2。
  • 为资源对象创建一个持有者。并如上解析它。想要完整的代码示例,请告诉我。
  • 我现在知道了,它有效,请检查我的 EDIT 3 是否这是一个聪明的解决方案。
猜你喜欢
  • 2021-08-26
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
相关资源
最近更新 更多