I have Json stored in javax.json.JsonObject, the object look like this:
{
"status":"ok",
"meta":{
"count":2
},
"data":{
"1":{
"id":40,
},
"17":{
"id":48,
}
}
}
How do I access the id key in the sub-object "1" ?
I tried:
obj.getJsonArray("data").getJsonArray("1").getJsonNumber("id").intValue();
However it does not work because the firt call of getJsonArray() method returns a JsonValue object not a JsonObject so the next call of getJsonArray fails. Any ideas ?
You can use an iterator approach to iterate thru the JSONObject:
JSONObject json = new JSONObject(input);
JSONObject jsonData = json.getJSONObject("data");
Iterator<?> jsonDataKeys = jsonData.keys();
while (jsonDataKeys.hasNext()) {
String key = (String)jsonDataKeys.next();
if (jsonData.get(key) instanceof JSONObject) {
System.out.println(((JSONObject) jsonData.get(key)).getInt("id"));
}
}
int id = obj.getJsonObject("data")
.getJsonObject("1")
.getInt("id");
JSONObject jObject = null;
jObject = new JSONObject(String you want to parse);
JSONObject j1Object = jObject.getJSONObject("data");
JSONObject j2Object = j1Object.getJSONObject("1");
String s1=j2Object.getString("id");
System.out.println(s1);
Related
So the json look like this
{
"cover":"AddressBook",
"Addresses":[
{
"id":"1",
"NickName":"Rahul",
"ContactName":"Dravid",
"Company":"Cricket",
"City":"Indore",
"Country":"India",
"Type":"Address"
},
{
"id":"2",
"NickName":"Sachin",
"ContactName":"Tendulkar",
"Company":"Cricket",
"City":"Mumbai",
"Country":"India",
"Type":"Address"
}
]
}
I want to extract the data from the id = 1 using the JSON array, but I am not sure how to use the syntax or some other way the code I have is this :
JSONParser jsonParser = new JSONParser();
FileReader reader = new FileReader("AddressBook.json");
Object obj = jsonParser.parse(reader);
address = (JSONArray)obj;
You have to loop through the "Addresses" array.
JSONObject addressBook = (JSONObject) jsonParser.parse(reader);
JSONArray addresses = (JSONArray) addressBook.get("Addresses");
JSONObject address = null;
for (Object find : addresses) {
if (((JSONObject) find).get("id").equals("1")) {
address = (JSONObject) find;
}
}
System.out.println(address.toJSONString());
Output
{"Company":"Cricket","Type":"Address","Country":"India","id":"1","City":"Indore","NickName":"Rahul","ContactName":"Dravid"}
i am trying to phrase the below json response and the get the "message" and "WORKORDERID" data in java
{
"operation": {
"result": {
"message": " successfully.",
"status": "Success"
},
"Details": {
"SUBJECT": "qqq",
"WORKORDERID": "800841"
}
}
}
Below is my code
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject jsonobject = (JSONObject) inputs.get("operation");
String s = jsonobject.getString("message");
system.out.println("s");
Your objects are nested 2 times, therefore you should do:
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject operation= (JSONObject) inputs.get("operation");
JSONObject result= (JSONObject) operation.get("result");
JSONObject details= (JSONObject) operation.get("Details");
String message = result.getString("message");
String workerId = details.getString("WORKORDERID");
JSONObject is somethink like Map-Wrapper, so you can think, that your JSON data-structure is Map<Map<Map<String, Object>, Object>, Object>. So, firstly you need to access to datas by first key (operation), secondly (result) and after that, you can access to desired field (message).
Note, that value of Map is Object, so you will need to cast your type to JSONObject.
sometimes JSONObject class is not found in java. so you will need to add jar
try{
// build the json object as follows
JSONObject jo = new JSONObject(jsonString);
// get operation as json object
JSONObject operation= (JSONObject) jo.get("operation");
// get result as json object
JSONObject result= (JSONObject) jo.get("result");
JSONObject details= (JSONObject) jo.get("Details");
// get string from the json object
String message = jo.getString("message");
String workerId = jo.getString("WORKORDERID");
}catch(JSONException e){
System.out.println(e.getMessage());
}
I'm currently trying to parse some JSON in my android application but I keep getting an error saying "No value for users"
This is the current code I am using:
JSONObject parentObject = new JSONObject(finalJSON);
JSONObject childObject = new JSONObject(String.valueOf(parentObject));
JSONArray parentArray = childObject.getJSONArray("users");
JSONObject finalObject = parentArray.getJSONObject(0);
String userName = finalObject.getString("username");
String profileLink = finalObject.getString("profileimage");
Log.d("JSON", String.valueOf(finalObject));
return profileimage+ " - " + profileLink ;
and here is my JSON:
{
"reply": {
"users": [
{
"userid": "001",
"loggedIn": 1,
"username": "joe.bloggs",
"profileimage": "http://127.0.0.1/joebloggs.png",
"realname": "Joe Bloggs",
}
]
}
}
Thanks in advance!
You forgot the reply level.
Here is what you should do.
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray userArray = parentObject
.getJSONObject("reply")
.getJSONArray("users");
JSONObject finalObject = userArray.getJSONObject(0);
you can't take new object for object inside object.
you have to do this for parse object inside object.
JSONObject object1 = new JSONObject(finalJSON);
JSONObject object2 = object1.getJSONObject("reply");
JSONArray jsonArray = object2.getJSONArray("users");
JSONObject object3 = jsonArray.getJSONObject(0);
try the following:
JSONObject root = null;
try {
root = new JSONObject("reply");
JSONArray childArray = root.getJSONArray("users");
String userName = childArray.getString(0);
.
.
.
} catch (JSONException e) {
e.printStackTrace();
}
Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.
https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.
This question already has answers here:
Accessing members of items in a JSONArray with Java
(6 answers)
Closed 6 years ago.
I am in a bit of a fix regarding the JSONObject that I am getting as a response from the server.
jsonObj = new JSONObject(resultString);
JSONObject sync_reponse = jsonObj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
String deleted_string = deletedtrs_array.toString();
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. i.e I want to extract companyid, username, date etc.
How can I go about this ?
Thanks for your input.
JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
for(int i = 0; deletedtrs_array.length(); i++){
JSONObject myObj = deletedtrs_array.getJSONObject(i);
}
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
The get companyid, username, date;
jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.