首页 > 解决方案 > 在处理中访问嵌套的 JSON

问题描述

我需要从 JSON 文件中提取 3 个值。我只是设法获取所有数据,但我无法将它们分开。该文件如下所示:

{
  "motionAndDeviceRelated":{
    "mOrientation":[0,0,0],
    "mLocalVelocity":[0,0,0],
    "mWorldVelocity":[0,0,0],
    "mAngularVelocity":[0,0,0],
    "mLocalAcceleration":[0,0,0],
    "mWorldAcceleration":[0,0,0],
    "mExtentsCentre":[0,0,0]
  }
}

我需要从 mLocalAcceleration 中提取浮点变量数据。

    import http.requests.*;
    JSONObject json;
  
    void setup() {
      size(600,600);
    }
     
    void draw() {
      // actually returns something instead of throwing an error, which is progress
      long t = System.currentTimeMillis();
      GetRequest get = new GetRequest("http://" + "localhost:8180/crest2/v1/api?motionDeviceRelated=true&formatted=true");
      get.send();
      JSONObject json = parseJSONObject(get.getContent());
      println(json);
      println(System.currentTimeMillis() - t);
      loop();
    }

标签: jsonnested

解决方案


这是有效的代码:

`import http.requests.*;
JSONObject json;
float x;
float y;
float z;

void setup() {
  size(800,800);
}
 
void draw() {
  long t = System.currentTimeMillis();
  GetRequest get = new GetRequest("http://" + "localhost:8180/crest2/v1/api?motionDeviceRelated=true&formatted=true");
  get.send();
  JSONObject json = parseJSONObject(get.getContent());  
  JSONObject motion = json.getJSONObject("motionAndDeviceRelated");
  JSONArray acc = motion.getJSONArray("mWorldAcceleration");
  x = acc.getFloat(0);
  z = acc.getFloat(1);
  y = acc.getFloat(2);
  println(System.currentTimeMillis() - t);
  loop();
}`

推荐阅读