JSON Parsing in Java Webservice of multiple JSONObjects in JSONObject - java

This is my JSON string,
{
"listmain":{
"16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}],
"17":[{"brandid":"1"}],
"18":[{"brandid":"12"},{"brandid":"186"}],
}
}
I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList.
What i meant is,
when we take "16", the following process should happen,
List<String> lsubid = new ArrayList<String>();
List<String> lbrandid = new ArrayList<String>();
for(int i=0;i<number of elements in "16";i++) {
lsubid.add("16");
lbrandid.add("ith value in tag "16" ");
}
finally the values in lsubid will be---> [16,16,16]
the values in lbrandid will be---> [186,146,15]
Can anyone please help me to complete this.

Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can parse the JSON like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONObject listMainObj = responseDataObj.getJSONObject("listmain");
Iterator keys = listMainObj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is 16,17,...
// get the value of the dynamic key
JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int i = 0; i < jsonrraySize; i++) {
JSONObject brandidObj = currentDynamicValue.getJSONObject(i);
String brandid = brandidObj.getString("brandid");
System.out.print("Brandid = " + brandid);
//store brandid in an arraylist
}
}
}
Source of this answer

Related

How to add two maps to the List

Code is:
How can to add the Map to the List
public List<Map<Object, Object>> getReportees(String idOfEmp) throws Exception {
JSONArray jsonarr_s = (JSONArray) jobj.get("list");
Map<Object, Object> map = new HashMap<Object, Object>();
if (jsonarr_s.size() > 0) {
// Get data for List array
for (int i = 0; i < jsonarr_s.size(); i++) {
JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
JSONObject jive = (JSONObject) jsonobj_1.get("jive");
Object names = jsonobj_1.get("displayName");
Object userid = jive.get("username");
map.put(names, userid); //return the map with the key value pairs
map = new HashMap<Object, Object>();
String UserId = userid.toString();
String output1 = resp1.getEntity(String.class);
JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);
// Store the JSON object in JSON array as objects (For level 1 array element i.e
// issues)
JSONArray jsonarr_new = (JSONArray) jobjs.get("issues");
int numofjiras = jsonarr_new.size(); //this jira count must be mapped to the name and id
map.put("count", numofjiras);
}
return map;
} else {
map.put("errorcheck", msg);
}
return map;
}
}
I want the output like:
Name id count
AJ 235457 2
Geet 637571 0
Actually I am getting the Name and id in key value pairs.Then I am trying to pass each id to an api which will give me the count.So how can I return all the fileds i.e Name ,id and count.So here I am trying to map like for this Userid and Name this is the count.How can we acheive it.Plesae help.Thanks in advnce.
I think you can try creating a new class to represent each row in your output. For example, you can create an Employee class like this:
public class Employee {
private long id;
private String name;
private int issueCount;
//getters and setters
}
You can, then, use this class and assign the values from the JSONArray arrays to it. Once you get the value for "count", you can just add the Employee object to the map (or list).
Hope this helps.
You would need to declare a local list first and then return that list:
public List<Map<Object, Object>> getReportees(String idOfEmp) throws Exception {
JSONArray jsonarr_s = (JSONArray) jobj.get("list");
Map<Object, Object> map = new HashMap<Object, Object>();
List<Map<Object, Object>> resultList = new ArrayList<Map<Object,Object>>();
if (jsonarr_s.size() > 0) {
// Get data for List array
for (int i = 0; i < jsonarr_s.size(); i++) {
JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
JSONObject jive = (JSONObject) jsonobj_1.get("jive");
Object names = jsonobj_1.get("displayName");
Object userid = jive.get("username");
map.put(names, userid); //return the map with the key value pairs
String UserId = userid.toString();
String output1 = resp1.getEntity(String.class);
JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);
// Store the JSON object in JSON array as objects (For level 1 array element i.e
// issues)
JSONArray jsonarr_new = (JSONArray) jobjs.get("issues");
int numofjiras = jsonarr_new.size(); //this jira count must be mapped to the name and id
map.put("count", numofjiras);
}
resultList.add(map);
} else {
map.put("errorcheck", msg);
resultList.add(map);
}
return resultList;
}
Based on your results though you should consider flipping your data objects to instead be
Map<Object, List<Object>>
where the first Object in the map which is they key the name and then the list would contain two objects [id, count].

JSONObject parse dictionary objects

JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air
Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.
try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");
Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.

Get values of jsonarray using other jsonarray values as a key

I'm getting following json from server:
{
"Data": [
{
"Record": [
" d11",
"d12"
]
},
{
"Record": [
" d21",
"d22"
]
}
],
"Keys": [
"Key1",
" key2"
]
}
I want to retrieve record values which are ordered with respect to keys values(key1, key2?
Note: Using org.json api only.
Your question is still a little unclear to me, but I'm assuming you want to turn that JSON into a list of records, where each record is (for example) a map containing the keys from the list of keys and the values from the data list.
In order to achieve this, we first parse the JSON into a JSONObject:
String json = " ... ";
JSONTokener tokener = new JSONTokener(json);
JSONObject jsonObject = new JSONObject(tokener);
Then we extract the list of keys and the data list:
JSONArray data = jsonObject.getJSONArray("Data");
JSONArray keys = jsonObject.getJSONArray("Keys");
and define a list to contain our output:
List<Map<String, String>> records = new ArrayList<>();
Finally, we iterate over the data list, extract the list of record values for each item in that list, and then iterate over the keys in order to create a map from key to record value:
for (int i = 0; i < data.length(); i++) {
JSONObject dataItem = data.getJSONObject(i);
JSONArray recordValues = dataItem.getJSONArray("Record");
Map<String, String> record = new HashMap<>();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
String value = recordValues.getString(j);
record.put(key, value);
}
records.add(record);
}
When we then print the value of records, we get something that looks like:
[{Key1= d11, key2=d12}, {Key1= d21, key2=d22}]

Convert JSON object with duplicate keys to JSON array

I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
For example
Input
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}
Output
{
"a":"b",
"c":["d","e"],
"f":"g"
}
The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
If possible, I'd like to do this without editing any library code
As of today the org.json library version 20170516 provides accumulate() method that stores the duplicate key entries into JSONArray
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("a", "b");
jsonObject.accumulate("c", "d");
jsonObject.accumulate("c", "e");
jsonObject.accumulate("f", "g");
System.out.println(jsonObject);
Output:
{
"a":"b",
"c":["d","e"],
"f":"g"
}
I want to remove the repeated keys by combining their values into an array.
Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into Map<String, List<String>> without using any library.
Sample code:
String jsonString = ...
// remove enclosing braces and double quotes
jsonString = jsonString.substring(2, jsonString.length() - 2);
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = keyValue[1];
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
output:
{
"f": ["g"],
"c": ["d","e"],
"a": ["b"]
}
In order to accomplish what you want, you need to create some sort of custom class since JSON cannot technically have 2 values at one key. Below is an example:
public class SomeClass {
Map<String, List<Object>> values = new HashMap<String, List<Object>>();
public void add(String key, Object o) {
List<Object> value = new ArrayList<Object>();
if (values.containsKey(key)) {
value = values.get(key);
}
value.add(o);
values.put(key, value);
}
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
JSONArray tempArray = null;
for (Entry<String, List<Object>> en : values.entrySet()) {
tempArray = new JSONArray();
for (Object o : en.getValue()) {
tempArray.add(o);
}
json.put(en.getKey(), tempArray);
}
return json;
}
}
You can then retrieve the values from the database, call the .add(String key, Object o) function with the column name from the database, and the value (as the Object param). Then call .toJson() when you are finished.
Thanks to Mike Elofson and Braj for helping me in the right direction. I only wanted to have the keys with multiple values become arrays so I had to modify the code a bit. Eventually I want it to work for nested JSON as well, as it currently assumes it is flat. However, the following code works for what I need it for at the moment.
public static String repeatedKeysToArrays(String jsonIn) throws JSONException
{
//This assumes that the json is flat
String jsonString = jsonIn.substring(2, jsonIn.length() - 2);
JSONObject obj = new JSONObject();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = "";
if (keyValue.length>1) value = keyValue[1];
if (!obj.has(key)) {
obj.put(key, value);
} else {
Object Oold = obj.get(key);
ArrayList<String> newlist = new ArrayList<String>();
//Try to cast as JSONArray. Otherwise, assume it is a String
if (Oold.getClass().equals(JSONArray.class)) {
JSONArray old = (JSONArray)Oold;
//Build replacement value
for (int i=0; i<old.length(); i++) {
newlist.add( old.getString(i) );
}
}
else if (Oold.getClass().equals(String.class)) newlist = new ArrayList<String>(Arrays.asList(new String[] {(String)Oold}));
newlist.add(value);
JSONArray newarr = new JSONArray( newlist );
obj.put(key,newarr);
}
}
return obj.toString();
}

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

Categories