JSON Object value is null - java

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();
}

Related

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 Volley PUT request is overriding everything

I am trying to update the remote JSON values using Volley for Android. Problem is that the code below completely overrides the whole JSON object.
File is located here: https://api.myjson.com/bins/kubxi
Original JSON file looks like this:
{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 1,
"action_2": 2,
"action_3": 3
}
]
},
{
"id": 2,
"name": "Name Two",
"actions": [
{
"action_1": 4,
"action_2": 5,
"action_3": 6
}
]
}
]
}
Java code
private void sendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
String url ="https://api.myjson.com/bins/kubxi"; // Remote JSON file
try {
jsonObject.put("action_1", 123);
jsonObject.put("action_2", 456);
jsonObject.put("action_3", 789);
} catch (JSONException e) {
Log.d("Exception", e.toString());
}
JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
)
{
#Override
public Map<String, String> getHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
try {
Log.i("JSON", jsonObject.toString());
return jsonObject.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
queue.add(putRequest);
}
After using this code, JSON file looks like this:
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
I was expecting for the code to only update the values on action_1, action_2 and action_3 from 1, 2, 3 to 123, 456, 789.
I want the JSON file to look like that after running the code:
{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
]
},
{
"id": 2,
"name": "Name Two",
"actions": [
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
]
}
]
}
Suggestions will be appreciated!
To update particular value in json file ,you can do like this:
Firstly take your original json in String :
String jsonString ="{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 1,
"action_2": 2,
"action_3": 3
}
]
}
]
}";
Next ,pass this String in JsonObject:
JSONObject jObject = new JSONObject(jsonString);//passing string to jsonobject
JSONArray jsonArray = jObject.getJSONArray("females");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonObject= object.getJSONArray("actions"); //getting action
array
for (int j = 0; j < jsonObject.length(); j++) {
JSONObject object1 = jsonObject.getJSONObject(j);
object1.put("action_1", 123); //here you are putting value to action_1
object1.put("action_2", 456);
object1.put("action_3", 789);
}
}
and then send this jsonObject to your server.

Taking user input retrieving details from json file and print it in java

Data.json:
{"UniversalWord": {"UniversalWord": [
{
"uw_id": 1,
"HeadWord": {"word": "aare"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aare"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
},
{
"uw_id": 2,
"HeadWord": {"word": "aarhus"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
},
{
"att": "restriction_type",
"value": "equ"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"PORT CITY OF DENMARK IN EASTERN JUTLAND\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aarhus"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
}
]}}
Required output:
Word Searched: aare
uwid = 1
headword = aare
semantic relation value = iof
target = ""
gloss = A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE
lemma = aare
example = ""
frequency = ""
Source_ID = wordnet
code.java
public class SearchJson
{
public void SearchValueInJson(StringBuilder sb)
{
try
{
String jsonData = sb.toString();
JSONObject jobj = new JSONObject(jsonData);
Map<String,String> map = new HashMap<String,String>();
iterateJson(jobj,map);
System.out.println(map.toString());
}
catch(Exception e)
{
System.out.println(e);
}
}
public void iterateJson(JSONObject jobj,Map map)
{
for(Object o : jobj.keySet())
{
if(jobj.get(o.toString())instanceof JSONObject)
iterateJson(jobj.getJSONObject(o.toString()),map);
else
map.put(o.toString(), jobj.get(o.toString()));
}
}
}
this code i tried but it is not giving me expected output.
How to retrieve this information from the json file? I'm not getting the proper solution for it. Please give code for this. And assume that you don't know key values of data on that basis have to retrieve.
Check the below code snippet, this may solve your problem.
JSONObject jobj = new JSONObject(jsonData);
JSONArray arr = jobj.getJSONObject("UniversalWord").getJSONArray("UniversalWord");
for (int i = 0; i < arr.length(); i++)
{
String uw_id = arr.getJSONObject(i).getString("uw_id");
System.out.println(uw_id);
String headWord = arr.getJSONObject(i).getJSONObject("HeadWord").getString("word");
System.out.println(headWord);
String nLDescription = arr.getJSONObject(i).getJSONObject("NLDescription").getJSONObject("Gloss").getJSONObject("feat").getString("val");
System.out.println(nLDescription);
}

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

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...

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