Android Json data parsing is ''[]'',Data parsing failed - java

Recently, I tried to code a list of linkman. I want to obtaining local data file(City.json) and parsing into listView. However ,the data from JsonObject always null. Help me please. I'm a Newbie. Thanks in advance.
the code under:
City.json
{
// "state": 1,
"datas": [
{
"id": "820",
"name": "安阳",
"sortKey": "A"
},
{
"id": "68",
"name": "安庆",
"sortKey": "A"
},
{
"id": "1269",
"name": "鞍山",
"sortKey": "A"
},
{
"id": "22",
"name": "蚌埠",
"sortKey": "B"
},
{
"id": "1372",
"name": "包头",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
}
]
}
AppFileReader.java
package me.sitinglin.administrator.wecharlinkmantest;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Created by Administrator on 2016/10/12.
*/
public class AppJsonFileReader {
public static String getJson(Context context, String fileName){
StringBuilder builder = new StringBuilder();
AssetManager manager = context.getAssets();
try {
InputStream stream = manager.open(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line = null;
while((line = bufferedReader.readLine())!=null){
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Log.i("abc", builder.toString());
return builder.toString();
}
public static List<City> setData(String str){
List<City> list = new ArrayList<>();
City city ;
try {
JSONObject result = new JSONObject(str);
JSONArray array = result.getJSONArray("datas");
// JSONArray array =new JSONArray(result);
int len = array.length();
Log.i("len", array.toString());
for (int i = 0; i <len ; i++) {
JSONObject object = array.optJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
}
}
this my context of logcat

Try this:
try {
JSONObject result = new JSONObject(str);
JSONArray jsonArray = result.getJSONArray("datas");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;

You should go with following code :
JSONObject jobj = new JSONObject(str);
if(jobj.has("datas")){
JSONArray jsonArray = jobj.getJSONArray("datas");
List<City> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jdataObj = jsonArray.getJSONObject(i);
City city = new City();
city.setId(jdataObj.getString("id"));
city.setName(jdataObj.getString("name"));
city.setSortKey(jdataObj.getString("sortKey"));
list.add(city);
}
} else {
Log.e("Json","Json has no datas key.")
}
Hope this will help you.

I found 3 solution to solve this.i will list 3 things that i've solved below and one of the 3 solutions may helped you.
there are three point which one of three point maybe help U :
1. checking out the [local file name] of JSON;
2. checking out variale is "public " or "private"..;
3.checking out some Json method whether you are uesing correct?
Aha...

Related

I want to add a new Object inside a Json Object in JAVA with JSONObject

Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]

Get data from nested JSON Object in Java Android

How I can get the "fields" objects 0,1,2,3,4 & only the "name" object string of every object using JSONOBJECT
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
& this is what I try to done
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
but the problem is, it gives me value of the object null like [value 4 is null] cuz there is no object for 4 in the first object of fields. please help me solve this prob, appreciate your answers thankyou :)
You can use keys() iterator of json object & loop on it using while (keys.hasNext())
For your example, it would look something like this:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
There are some problems with get all keys properly in my IDE/JDK11, so I decided to loop over an ArrayList, basing on #MayurGajra solution, ex:
private static List<List<String>> parseJson(String response) throws JSONException {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
List<Object> list = new ArrayList<>();
jo.keys().forEachRemaining(list::add);
List<String> subList = new ArrayList<>();
for (Object o : list) {
String key;
if (isString(o))
key = (String) o;
else
continue;
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
subList.add(f_name1);
}
result.add(subList);
}
return result;
}
private static boolean isString(Object o) {
try {
String result = (String) o;
} catch (ClassCastException e) {
return false;
}
return true;
}
The result obtained after processing the above json is as follows:
[[Email, City, Screenshot, Full Name], [Email, City, Screenshot, Submitted Date]]
but it have not to be a List of Lists ;)
-- edit --
To get only first list of elements labeled "name":
try {
System.out.println(parseJson(yourJsonAsString).get(0).toString());
} catch (JSONException e) {
System.out.println("JSONException:" + e.getMessage());
}
The result of above is:
[Email, City, Screenshot, Full Name]

JSON Object value is null

Please find below the code I am using to read from a JSON file and display it. The file contains some rules. I want to read the rules from the file and display it in the UI. But I am getting the output as follows:
Technology: null
Vulnerability: null
Severity: null
RegEx: null
The file Rule_File.json is not null and has values. But they are not getting read by this code. Any idea why this is happening? Please let me know your suggestions. Thanks in advance!
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSON_Reader
{
public static void main(String args[])
{
JSONParser parser = new JSONParser();
try
{
String text = new String(Files.readAllBytes(Paths.get("C:\\Users\\arathi.variar\\workspace\\Customizable_Rule_UI\\src\\Rule_File.json")), StandardCharsets.UTF_8);
Object object = parser.parse(text);
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
//Reading the String
String tech = (String) jsonObject.get("Technology");
String vul = (String) jsonObject.get("Vulnerability");
String sev = (String) jsonObject.get("Severity");
String regex = (String) jsonObject.get("RegEx");
//Printing all the values
System.out.println("Technology: " + tech);
System.out.println("Vulnerability: " + vul);
System.out.println("Severity: " + sev);
System.out.println("RegEx: " + regex);
}
catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Please find below my Rule_File.json
{
"Angular2": [
{
"Technology": "Angular 2.0",
"Vulnerability": "angular/timeout-service",
"Severity": 1,
"RegEx": "(?=.*(setTimeout))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "angular/interval-service",
"Severity": 1,
"RegEx": "(?=.*(setInterval))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "angular/Deferred",
"Severity": 1,
"RegEx": "(?=.*(\\$q\\.defer|\\$q\\_\\.defer))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "Cross Site Scripting",
"Severity": 1,
"RegEx": "(?=.*(body.*ng-app.*|\\$sceProvider\\.enabled\\(\\s*false\\)))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "angular/Angular Element",
"Severity": 1,
"RegEx": "(?=.*(\\$\\('.*'\\)|jQuery\\('.*'\\)))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "Module Setter",
"Severity": 1,
"RegEx": "(?=.*(var\\s*[a-zA-Z0-9_]+\\s*=\\s*angular.module\\(.*\\)))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "Sensitive Data",
"Severity": 1,
"RegEx": "(?=.*(store\\.set\\())"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "no-cookiestore",
"Severity": 3,
"RegEx": "(?=.*(\\$cookieStore\\s*\\.))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "no-directive-replace",
"Severity": 3,
"RegEx": "(?=.*((replace\\s*\\:\\s*true)|(\\.replace\\s*\\=\\s*true)))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "no-http-callback",
"Severity": 3,
"RegEx": "(?=.*(\\$http\\..*\\.(success|error)))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "defined/undefined",
"Severity": 3,
"RegEx": "(?=.*((value\\s*(\\!|\\=)\\=\\=\\s*undefined)|(\\!angular\\.is(Defined|Undefined))))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "json functions",
"Severity": 3,
"RegEx": "(?=.*(JSON\\.))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "Console Log",
"Severity": 3,
"RegEx": "(?=.*(console\\.))"
},
{
"Technology": "Angular 2.0",
"Vulnerability": "no-angular-mock",
"Severity": 3,
"RegEx": "(?=.*(angular\\.mock))"
}
],
"reactJS": [
{
"Technology": "React JS",
"Vulnerability": "Cross Site Scripting",
"Severity": 1,
"RegEx": "(?=.*(window.\\_\\_PRELOADED\\_STATE\\_\\_\\s*=\\s*\\$\\{JSON.Stringify\\(preloadedState\\)}))"
}
],
"javascript": [
{
"Technology": "JAVA/JAVAScript",
"Vulnerability": "URL Injection",
"Severity": 1,
"RegEx": "(?=.*(Request.QueryString[\"[a-zA-Z]+\"];))"
},
{
"Technology": "JAVA/JAVAScript",
"Vulnerability": "Weak Credentials",
"Severity": 1,
"RegEx": "(?=.*((user(name|id)?|logon(id)?)\\s*=\\s*((\\\"|\\').+(\\\"|\\'))))"
}
]
}
You need to find the JSONObject in the array first. You are trying to find the fields of the top-level JSONObject, which only contains the field Angular2, reactJS, javascript so it is returning null because it can't find fields technology,vulnerability...
JSONObject jsonObject1 = (JSONObject) object;
JSONArray fields= (JSONArray) jsonObject1.get("Angular2");
for (Object field: fields) {
JSONObject jsonObject = (JSONObject) field;
//Reading the String
String tech = (String) jsonObject.get("Technology");
String vul = (String) jsonObject.get("Vulnerability");
String sev = (String) jsonObject.get("Severity");
String regex = (String) jsonObject.get("RegEx");
//Printing all the values
System.out.println("Technology: " + tech);
System.out.println("Vulnerability: " + vul);
System.out.println("Severity: " + sev);
System.out.println("RegEx: " + regex);
}
Your intended values are within an Array andneed to be accessed that way.
JSONArray array = (JSONArray)jsonObject.get("Angular2");
for(Object obj : array.toArray()){
JSONObject jObj = (JSONObject)obj;
System.out.println(String.format("Technology:%s, Vulnerability:%s, Severity:%s, RegEx:%s", jObj.get("Technology"),jObj.get("Vulnerability"),jObj.get("Severity"),jObj.get("RegEx")));
}
On a different note, Jackson could help in simplifying object mapping to POJOs.
You can try using JSONObject and JSONArray as an alternative. Here is how I would approach this problem, hope it helps :)
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
// Use these instead as an alternative:
import org.json.JSONArray;
import org.json.JSONObject;
//import org.json.simple.parser.JSONParser;
public class JSON_Reader
{
public static void readJSONArray () {
try
{
String text = new String(Files.readAllBytes(Paths.get("Rule_File.json")), StandardCharsets.UTF_8);
JSONObject jobj = new JSONObject(text);
Iterator keys = jobj.keys();
while (keys.hasNext()) {
String key = (String) (keys.next());
JSONArray arr = jobj.getJSONArray(key);
for (int i = 0; i < arr.length(); i++) {
//convert Object to JSONObject
JSONObject jsonObject = arr.getJSONObject(i);
//Reading the String
String tech = (String) jsonObject.get("Technology");
String vul = (String) jsonObject.get("Vulnerability");
Integer sev = (Integer) jsonObject.get("Severity");
String regex = (String) jsonObject.get("RegEx");
//Printing all the values
System.out.println("Technology: " + tech);
System.out.println("Vulnerability: " + vul);
System.out.println("Severity: " + sev);
System.out.println("RegEx: " + regex);
}
}
}
catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
readJSONArray();
}
}
Try this
JSONObject jsonObject = (JSONObject) object;
try {
JSONArray jsonArray= (JSONArray)jsonObject.get("Angular2");
for (Object object: jsonArray) {
JSONObject angular = (JSONObject) object;
String tech = (String) angular.get("Technology");
String vul = (String) angular.get("Vulnerability");
String sev = (String) angular.get("Severity");
String regex = (String) angular.get("RegEx");
}
} catch (JSONException e) {
e.printStackTrace();
}

Retrieving string from nested objects in JSON file || Android

I'm having trouble trying to access certain values in a JSON file.
The file has multiple objects stored inside an array.
The value I need to return is "60" inside the "maxspeed" string.
When the current code is executed in debug it just remains in a loop.*Not sure why)
The value of the "result" string is the entire json file.
Would anyone be able to explain how to access this value?
Thanks.
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T00:27:03Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}
Code:
protected Void doInBackground(String... params) {
android.os.Debug.waitForDebugger();
//String url_select = "http://yoururlhere.com";
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(encode2);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line); } }
else {
Log.e("==>", "Failed to download file"); }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
result = builder.toString();
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
JSONObject maxspeed = parentObject.getJSONObject("maxspeed");
System.out.print(""+maxspeed.toString()+"\n");
//String[] elementNames = JSONObject.(speedJSON);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", speedJSON.length());
for (int i = 0; i< speedJSON.length(); i++)
{
String value = speedJSON.getString(i);
System.out.printf("name=%s, value=%s\n", speedJSON.get(i), value);
}
//And then read attributes like
/* for(int i = 0; i<speedJSON.length(); i++){
JSONObject child = speedJSON.getJSONObject(i);
if(child.getString("type").equals("way")){
JSONObject tag = speedJSON.getJSONObject(i);
JSONObject maxspeed = tag.getJSONObject("tags");
String speed = maxspeed.getString("maxspeed");
txtSpeed.setText(speed);
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String speedLimit = jObject.getString("maxspeed");
txtSpeed.setText(speedLimit);
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
*/ } // protected void onPostExecute(Void v)
}
Okay your first problem is that not all JSONObjects from your "elements" array have a max speed property. The second problem is that you are not iterating over your JSONArray correctly.
Lets start with the second proble:
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
}
Now your element is the JSONObject which contains your different properties (type, id, lon, ...)
To solve your first problem you can check if a JSONObject contains the key you are looking for (maxspeed)
if (!element.isNull("tags") {
JSONObject tags = (JSONObject)element.get("tags");
if (!tags.isNull("maxspeed") {
String maxspeed = tags.getString("maxspeed");
}
} else {
//Your error handling here...
}
Hope this helps!

Dynamically generated JSON Order is missing

With the values present inside the Map DataStructure i am creating a JSON dynamically .
The JSON its getting created is
{
"item": {
"T1": [
{
"name": "Ice creams",
"T2": [
{
"name": "Ice creams***Stick",
"T3": [
{
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
],
"name": "Ice creams***Stick***KoolCool"
}
]
}
]
}
]
}
}
The problem is that the name under T3 is being appended at some other place rather than after it ,which should actually be
{
"item": {
"T1": [
{
"name": "Ice creams",
"T2": [
{
"name": "Ice creams***Stick",
"T3": [
{
"name": "Ice creams***Stick***KoolCool",
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
]
}
]
}
]
}
]
}
}
Functionally there should be no difference between name being first or second in the property list,but this JSON would be passed to the Front End and the search functionality is breaking down ,if it not follows the structure
could anybody please let me know how to make the name appear after T3 ??
Please see this fiddle
http://jsfiddle.net/5wvqkb82/
This is my Java Program.
package com.services;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
private static JSONObject processString(String data, int level,String key) throws JSONException {
JSONObject json = new JSONObject();
JSONArray leafjsonarray = new JSONArray();
int index = data.indexOf(',');
String name = data;
String remainder = "";
if (index < 0) {
index = name.indexOf('(');
if (index > 0) {
name = data.substring(0, index);
}
} else {
name = data.substring(0, index);
remainder = data.substring(name.length() + 1);
}
String fullpath = key+"***"+name;
json.put("name", fullpath);
JSONArray a = new JSONArray();
if (remainder.length() > 0) {
a.put(processString(remainder, level + 1,fullpath));
json.put("T" + level, a);
}
else {
JSONObject leafjsonObj = new JSONObject();
leafjsonObj.put("crust_name", "crust");
leafjsonarray.put(leafjsonObj);
json.put("leaf", leafjsonarray);
}
return json;
}
private static JSONArray processList(List<String> list, int level,String key) throws JSONException {
JSONArray json = new JSONArray();
for (String data : list) {
json.put(processString(data, level,key));
}
return json;
}
private static JSONArray processMap(Map<String, List<String>> map, int level) throws JSONException {
JSONArray array =new JSONArray();
for (String key : map.keySet()) {
JSONObject json = new JSONObject();
json.put("name", key);
json.put("T" + level, processList(map.get(key), level + 1,key));
array.put(json);
}
return array;
}
public static void main(String args[]) {
Map<String, List<String>> consilatedMapMap = new LinkedHashMap<String, List<String>>();
List<String> values = new LinkedList<String>();
values.add("Stick,KoolCool,Strawbeerry(25)");
// values.add("Cone,SSS(25)");
/* List<String> values2 = new LinkedList<String>();
values2.add("Bucket(25)");
*/
//consilatedMapMap.put("Popcorn", values2);
consilatedMapMap.put("Ice creams", values);
try {
int level = 2;
JSONArray json = processMap(consilatedMapMap, level);
JSONObject jsonT1 = new JSONObject();
jsonT1.put("T1",json);
JSONObject sai = new JSONObject();
sai.put("item",jsonT1);
System.out.println(sai);
} catch(JSONException x) {
x.printStackTrace();
System.exit(-1);
}
}
}
You need to take a look at this. Basically, you cannot rely on the order of the objects. If you need them to be in an order, you should use JSON Arrays.
If you want to use Arrays, your whole ordering will be messed up, for example:
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry",
"leaf": [
{
"crust_name": "crust"
}
]
}
]
will become
"T4": [
{
"name": "Ice creams***Stick***KoolCool***Strawbeerry"
},
{
"leaf": [
{
"crust_name": "crust"
}
]
}
]
You have used JSON Arrays in your program, make use of it and figure it out if you really want to go ahead with this way.

Categories