Reputation: 3
I have a JSONObject
and want to get a String
out of it and save it.
SelVehicleJSON (JSONObject):
{
"selVehicle":
{
"_id":"5b38be73257303206ce9b8f9",
"userId":"5b34c591cb6084255857e338"
}
}
I tried
String vehicleId = selVehicleJSON.getString("_id");
but I get the error
W/System.err: org.json.JSONException: No value for _id`.
What am I doing wrong?
Upvotes: 0
Views: 165
Reputation: 2699
The hierarchy seems to be
selVehicle._id
Or set the root before doing
selVehicleJSON.getString("_id");
Edit 1
Try using JsonPath. It makes the life easier and keeps the code clean. In your case, the code will look like:
public String getValue(JSONObject json, String path) {
return JsonPath.read(json.toString(), path);
}
Upvotes: 1
Reputation: 457
You have two json objects. The outer one is selVehicle and there is a inner json object. So first get the outer json object and use getString on the returned json object.
Try to use this:
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"));
Upvotes: 0
Reputation: 875
You should try this :
JSONObject selVehicle = selVehicleJSON.get("selVehicle");
String id = selVehicle.get("_id");
Upvotes: 0