简体   繁体   English

如何从JsonObject Java恢复值

[英]How to recover values from JsonObject java

I have a list of JSonObject, I want recover just the values of tow variables in json. 我有一个JSonObject列表,我想仅恢复json中的tow变量的值。

In java 8 I don't find the function getJSONObject,may be it's not recognized.. First of all I added my json to a list of JSONObject . 在Java 8中,我找不到函数getJSONObject,可能是无法识别。.首先,我将json添加到JSONObject列表中。 But when I want get it, the editor Intellij propose just the function get. 但是,当我想要获取它时,编辑器Intellij仅提出函数get。

Exemple: records.get(0).get("id") I got the result bellow, but when I want recover the varible inside like: records.get(0).get("id").get("875488")... I got an error. 例如: records.get(0).get("id")我得到了下面的结果,但是当我想要恢复内部变量时,就像: records.get(0).get("id").get("875488")...我遇到了错误。

My code:


JSONArray JSONArray = (JSONArray) obj;
List<JSONObject> records = new ArrayList<JSONObject>(); 

    for (int i=0; i<JSONArray.size(); i++) {

        records.add( (JSONObject) JSONArray.get(i) );

    }

I tried to recover the first tow value of "lat" and "lon" but I can't arrived. 我试图恢复"lat""lon"的第一个拖曳值,但我无法到达。 Someone can help me please ? 有人可以帮我吗?

I want like as result: 我想要作为结果:

lat = 12.13

lon =  5.02

Thank you. 谢谢。

First off all, the correct Maven/Gradle dependency for JAVA-json is 首先,对于JAVA-json正确的Maven / Gradle依赖关系是

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

If the method JSONObject#getJSONObject cannot be found, you're doing something wrong. 如果找不到JSONObject#getJSONObject方法,则说明您做错了。


For the code part, that should do it. 对于代码部分,应该这样做。 Adapt to your necessities. 适应您的必需品。

final JSONArray jsonArray = new JSONArray(source);
final int length = jsonArray.length();

for (int i = 0; i < length; i++) {
    final JSONObject jsonObject = jsonArray.getJSONObject(i);
    final JSONObject forecastOrig =
            jsonObject.getJSONObject("875488")
                      .getJSONObject("forecast_orig");

    final double lon = forecastOrig.getDouble("lon");
    final double lat = forecastOrig.getDouble("lat");

    System.out.println(lon);
    System.out.println(lat);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM