从JSONObject获取数据

时间:2018-07-04 14:46:53

标签: java json

我有一个JSONObject,想从中取出一个String并保存它。

SelVehicleJSON (JSONObject):
{
  "selVehicle":
  {
     "_id":"5b38be73257303206ce9b8f9",
     "userId":"5b34c591cb6084255857e338"
  }
}

我尝试过

String vehicleId = selVehicleJSON.getString("_id");

但是我得到了错误

  

W / System.err:org.json.JSONException:_id`无值。

我在做什么错了?

3 个答案:

答案 0 :(得分:1)

层次结构似乎是

  

selVehicle._id

或在执行操作之前设置根目录

  

selVehicleJSON.getString(“ _ id”);

编辑1

尝试使用JsonPath。它使工作更轻松,并使代码保持干净。 就您而言,代码如下:

public String getValue(JSONObject json, String path) {
    return JsonPath.read(json.toString(), path);
}

答案 1 :(得分:0)

您应该尝试:

JSONObject selVehicle =  selVehicleJSON.get("selVehicle");

String id = selVehicle.get("_id");

答案 2 :(得分:0)

您有两个json对象。外部是selVehicle,内部有一个json对象。因此,首先获取外部json对象,并在返回的json对象上使用getString。

尝试使用此功能:

import java.io.File;
import static org.apache.commons.io.FileUtils.readFileToString;
import org.json.JSONObject;

File file = new File("Input your json filePath here");
String text = readFileToString(file);
JSONObject jsonObject = new JSONObject(text);
jsonObject = jsonObject.getJSONObject("selVehicle");
System.out.println(jsonObject.getString("_id"));
相关问题