简体   繁体   English

在Java中将Json对象放入Json对象中

[英]Getting Json object inside a Json object in Java

So I have some code that is able to send this out: 所以我有一些能够发送出去的代码:

  {"id":1,
   "method":"addWaypoint",
   "jsonrpc":"2.0",
   "params":[
     {
       "lon":2,
       "name":"name",
       "lat":1,
       "ele":3
     }
    ]
   }

The server receives this JSON object as a string named "clientstring": 服务器将此JSON对象作为名为“clientstring”的字符串接收:

 JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
 String method = obj.getString("method"); //Pulls out the corresponding method

Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method". 现在,我希望能够得到{“lon”的“params”值:2,“name”:“name”,“lat”:1,“ele”:3}就像我得到的方法一样”。 however both of these have given me exceptions: 但是这两个都给了我例外:

String params = obj.getString("params");

and

 JSONObject params = obj.getJSONObject("params");

I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? 我真的不知道如何存储和使用{“lon”:2,“name”:“name”,“lat”:1,“ele”:3}没有异常,它是合法的JSON而它不能存储为JSONObject? I dont understand. 我不明白

Any help is VERY appreciated, thanks! 任何帮助都非常感谢,谢谢!

params in your case is not a JSONObject , but it is a JSONArray . 在你的情况下, params 不是 JSONObject ,但它是一个JSONArray

So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject . 所以你需要做的就是首先获取JSONArray ,然后获取该数组的第一个元素作为JSONObject

JSONObject obj = new JSONObject(clientstring); 
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);

How try like that 怎么这样尝试

    JSONObject obj = new JSONObject(clientstring);
    JSONArray paramsArr = obj.getJSONArray("params");


    JSONObject param1 = paramsArr.getJSONObject(0);

    //now get required values by key
    System.out.println(param1.getInt("lon"));
    System.out.println(param1.getString("name"));
    System.out.println(param1.getInt("lat"));
    System.out.println(param1.getInt("ele"));

Here "params" is not an object but an array. 这里“params”不是一个对象而是一个数组。 So you have to parse using: 所以你必须解析使用:

JSONArray jsondata = obj.getJSONArray("params");

for (int j = 0; j < jsondata.length(); j++) {
    JSONObject obj1 = jsondata.getJSONObject(j);
    String longitude = obj1.getString("lon");
    String name = obj1.getString("name");
    String latitude = obj1.getString("lat");
    String element = obj1.getString("ele");
  }

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

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