parsing JSONArray with multiple values in android - java

I have a JSONfile like :
{ "data" :
{ "stop1" : [ "elem1", "elem2", "elem3", "elem4"],
"stop2" : [ "selem1", "selem2", "selem3", "selem4"]
}
}
For parsing this file I have written the following code:-
HashMap<String, String> stopList = new HashMap<>();
JSONObject dataJsonObj = (new JSONObject(json)).getJSONObject("data");
JSONArray busStopJsonObj, urlJsonObj;
busStopJsonObj = dataJsonObj .getJSONArray("stop1");
urlJsonObj = dataJsonObj .getJSONArray("stop2");
for (int i = 0; i < busStopJsonObj.length(); i++)
stopList.put(busStopJsonObj.getString(i), urlJsonObj.getString(i));
However i get an error as:
org.json.JSONException: Value {"stop1":["elem1","elem2"
org.json.JSON.typeMismatch(JSON.java:100)
org.json.JSONArray.getJSONArray(JSONArray.java:500)

Seems like your JSON is invalid. The correct JSON should be:
{"data": {
"stop1": [
"elem1",
"elem2",
"elem3",
"elem4"
],
"stop2": [
"selem1",
"selem2",
"selem3",
"selem4"
]
}
}

Related

Add new key,value and update existing value of key in JSON file in java

My json file contains data as below : filename: "masterData.json"
{
"Devices":[
{"DeviceID":"WS1272765443SA",
"DeviceModel":"model",
"SerialNumber":"121",
"Status":"available"
},
{
"DeviceID":"WS1215",
"DeviceModel":"eCP Tablet",
"SerialNumber":"122",
"Status":"available"
}
],
"Organization":[
{
"OrgName":"abc",
"UserName":"hello",
"OrgId":"abc",
"CommunityURL":"",
"ApiVersionValue":"1.0",
"OrgCode":"Orgcode11",
"OrgType":"en",
"NameSpace":"h",
}
],
"DeviceModels":[
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
},
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
}
]
}
I need to add deviceNumber and value for each of my devices and also update the Status from available to active so that my "masterData.json" would look like
{
"Devices":[
{
"DeviceID":"WS1272765443SA",
"DeviceModel":"model",
"SerialNumber":"121",
"Status":**"active"**,
**"deviceNumber":"123456D"**
},
{
"DeviceID":"WS1215",
"DeviceModel":"eCP Tablet",
"SerialNumber":"122",
"Status":**active**,
**"deviceNumber":"1234f"**
}
],
"Organization":[
{
"OrgName":"abc",
"UserName":"hello",
"OrgId":"abc",
"CommunityURL":"",
"ApiVersionValue":"1.0",
"OrgCode":"Orgcode11",
"OrgType":"en",
"NameSpace":"h",
}
],
"DeviceModels":[
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
},
{
"BrandName":"",
"ModelNameValue":"",
"Config":""
}
]
}
Kindly help me with the java code.
i tried with below java code and couldn't achieve.
FileReader reader = new FileReader(utility.getValue("MasterJsonPath"));
JsonObject jsonObj = (JsonObject) parser.parse(reader);
JsonArray deviceListFromJSON = (JsonArray) jsonObj.get("Devices");
for (int i = 0; i < deviceListFromJSON.size(); i++) {
JsonObject devices = (JsonObject) deviceListFromJSON.get(i);
ObjectMapper mapper = new ObjectMapper();
devices.addProperty("device number", "device value");
deviceListFromJSON.add(devices);
mapper.writer().writeValue(new File(utility.getValue("MasterJsonPath")),deviceListFromJSON);
}
}
First of , your fisrt json code is malformed ( extra commas , missing {"Devices" , .. ).
I tried to correct it :
{"Devices": [
{"DeviceID":"WS1272765443SA",
"DeviceModel":"model",
"SerialNumber":"121",
"Status":"available"
},
{"DeviceID":"WS1215",
"DeviceModel":"eCP Tablet",
"SerialNumber":"122",
"Status":"available"
}],
"Organization": [
{"OrgName":"abc",
"UserName":"hello",
"OrgId":"abc",
"CommunityURL":"",
"ApiVersionValue":"1.0",
"OrgCode":"Orgcode11",
"OrgType":"en",
"NameSpace":"h"
}],
"DeviceModels":[
{"BrandName":"",
"ModelNameValue":"",
"Config":""
},
{"BrandName":"",
"ModelNameValue":"",
"Config":""
}]}
For the java Code , try to save the file at the end of the for loop.
And write the whole jsonobject "jsonObj" , not only the deviceListFromJSON.
Also , use addProperty on both "deviceNumber" and "Status".Hope it helps :)
FileReader reader = new FileReader("file.json");
JsonParser parser = new JsonParser() ;
JsonObject jsonObj = (JsonObject) parser.parse(reader);
JsonArray deviceListFromJSON = (JsonArray) jsonObj.get("Devices");
reader.close();
for (int i = 0; i < deviceListFromJSON.size(); i++) {
JsonObject devices = (JsonObject) deviceListFromJSON.get(i);
devices.addProperty("deviceNumber", "1234f");
devices.addProperty("Status", "active");
}
BufferedWriter writer = new BufferedWriter(new FileWriter("file.json"));
writer.write(jsonObj.toString());
writer.close();

Java Implementation of JsonLogic Not Working

Has anyone successfully used the Java implementation of JsonLogic?
This rule
{"==" : [ { "var" : "code" }, "ER"]}
gives the correct answer (true) with this data
{"code": "ER", "name": "Exploratory Research"}
using the javascript playground.
However, this Java code
JavaJsonLogic jsonLogic = JavaJsonLogic.INSTANCE;
String rule = "{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]}";
JsonObject data = new JsonObject();
data.addProperty("code", "ER");
data.addProperty("name", "Exploratory Research")
System.out.println(jsonLogic.apply(rule, data)););
returns false!
JsonLogic jsonLogic = new JsonLogic();
String rule = "{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]}";
//JsonObject data = new JsonObject();
Map<String, Object> data = new HashMap<>();
data.put("name", "Exploratory Research");
data.put("code", "ER");
jsonLogic.apply(rule, data);
I am using a hashmap to populate value in place of JsonObject. And the result is coming out as true. And also i am using https://mvnrepository.com/artifact/io.github.jamsesso for parsing jsonLogic string and validating the data over jsonlogic.
dmillerw too did the jsonlogic implementation for java based off of jsonlogic spec that you were following. I just tried by picking up the code base from below URL and with your test data, it is working like a charm.
https://github.com/dmillerw/json-logic-java
Here is what I had in my junit to test your need:
String testjson = **"[[{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]},{\"code\": \"ER\", \"name\": \"Exploratory Research\"},true]]";**
JsonArray testArray = gson.fromJson(testjson, JsonArray.class);
for (JsonElement element : testArray) {
JsonArray array = element.getAsJsonArray();
JsonElement test = array.get(0);
JsonElement data = array.get(1);
JsonElement expected = array.get(2);
System.out.println(**JsonLogic.apply(test, data)**);
}

How to Parse this json object nested in json array

I am using this code
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
bookItems bookItem = new bookItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
JSONObject bookChapter = jsonObject.getJSONObject("chapter");
bookItem.setbook_subtitle(bookChapter.getString("subtitle"));
JSONObject chapVerses = jsonObject.getJSONObject("verses");
JSONArray verseReaders = chapVerses.getJSONArray("readers");
JSONObject readersNum = verseReaders.getJSONObject("number");
verseReadNum = readersNum;
} catch (JSONException w) {
w.printStackTrace();
}
mbookItemsList.add(bookItem);
}
}
to parse this json.
[
{
"chapter": {
"subtitle": "Something happened in this in this chapter"
},
"verses": {
"about": [
{
"In this verse, a lot of things happened yes a lot!"
}
],
"readers": [
{
"read": false,
"number": "No body has read this verse yet"
}
],
}
},
...]
I am getting the "subtitle" correctly but I am having didfficulty getting "number".
From line JSONObject readersNum = verseReaders.getJSONObject("number"); Android studio is complaining that getJSONOBJECT (int) in JSONArray cannnot be applied to (java.lang.String)
Please, how do I properly parse this?
verseReaders is a JSONArray, so you need to iterate over (or take the first) JSONObject and then get the string from that object.
String readersNum = verseReaders.getJSONObject(0).getString("number");
You have to use nested loops. Just add one more for for "readers".

Using Json to access a specific attribute

Hello guys i'm reading a page that contain JSON objects with JAVA (Android)
Here is what the page contains :
{
"destination_addresses" : [ "Safi, Maroc" ],
"origin_addresses" : [ "Avenue Hassan II, Safi, Maroc" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,0 km",
"value" : 966
},
"duration" : {
"text" : "2 minutes",
"value" : 129
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I know how to read from the page doing this
JSONObject jArray = new JSONObject(result);
String elements = jArray.getString("rows");
the elements string contain that :
[{"elements" : [{"distance" : {"text" : "1,0 km","value" : 966},"duration" : {"text" : "2 minutes","value" : 129},"status" : "OK"}]}]
But im trying to get the distance value which is "966"
Thx guys
So you are trying to access an entry from the array. See Tutorials or examples. This is basic stuff:
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
You need to actually use a JSONArray (which subclasses JSONObject)
You might want to take a look at this link:
How to parse JSON in Android
But for your particular problem you want to call something like:
int value = jArray.getJSONObject("rows").getJSONObject("elements").getJSONArray("distance").getInteger("value");
Try this..
JSONObject jObj = new JSONObject(result);
JSONArray rows = jObj.getJSONArray("rows");
for(int i = 0; i < rows.length; i++){
JSONObject obj = rows.getJSONObject(i);
JSONArray elements = jObj.getJSONArray("elements");
for(int j = 0; j < elements.length; j++){
JSONObject Jobj = elements.getJSONObject(j);
JSONObject distance = Jobj.getJSONObject("distance");
int distance_value = distance.getInteger("value");
JSONObject duration = Jobj.getJSONObject("duration");
int duration_value = duration.getInteger("value");
}
}

issue in looping

I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.
output :
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
code :
public class MyFormToJSONConverter {
public JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
List<JSONArray> list = new ArrayList<JSONArray>();
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
formDetailsJson.put("desc",
form.get(i).getFormDescription());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
}
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
return responseDetailsJson;
}
Your problem is here:
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
will overwrite all of the previous values with the next value (a single JSON object). You want
responseDetailsJson.put("form", list);
You probably should also get rid of this:
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
That will give you:
{
"forms": [
[{ "form_id": "1", "form_name": "test1" }],
[{ "form_id": "2", "form_name": "test2" }]
]
}
All told, I think you want:
JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList
// instead of an ArrayList.
for (Form formInstance:form) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", formInstance.getId());
formDetailsJson.put("form_name", formInstance.getName());
formDetailsJson.put("desc",
formInstance.getFormDescription());
list.add(formDetailsJson);
}
responseDetailsJson.put("form", list);
JSON objects are essentially key/value pairs. In your code you are doing:
for (JSONArray json : list)
{
responseDetailsJson.put("form", json);
}
You're overwriting the same key each time.

Categories

Resources