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}]
Related
Code:
Map<String, Integer> map = new LinkedHashMap<>();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject list = jsonArray.getJSONObject(j);
String key = list.getString("symbol") + list.getString("groupname");
if (!map.containsKey(key)) {
map.put(key, list.getInt("openqty"));
} else {
int val = map.get(key) + list.getInt("openqty");
map.put(key, val);
}
System.out.println("map " + map);
}
// Converted map into jsonstring
String jsonString = new JSONObject(map).toString();
System.out.println("jsonstring " + jsonString);
Output:
{"SILVERRohit":0,"DINRCosmic":20,"NATURALGASCosmic":0,"NGCosmic":0,"SICosmic":-5,"SILVERCosmic":35,"DINRRishi":0,"SIRishi":0,"SILVERRishi":0,"CLAmitTA":-6,
"CRUDEOILAmitTA":60,"DINRAmitTA":24,"GCAmitTA":0,"GOLDAmitTA":0,"SIAmitTA":0,"SILVERAmitTA":0,"DINRPraveen":0,"GCPraveen":0,"GOLDPraveen":0,"DINRHarsh":46,
"GCHarsh":-9,"GOLDHarsh":28,"SIHarsh":9,"SILVERHarsh":-45,"DINRGovind":-160,"SIGovind":11}
^^ this is an jsonobject I have got by using linkedhashmap. So, now my problem is I want to convert it into jsonArray format to set in the model (recyclerview). I have also tried by iterating, but I am getting the same values in each single row.
Not only this, but also I want to change all jsonobject keys to "open", so that I can use this in recyclerview for each single row.
Expected output:
[ {"open":0},{"open":20} , {"open":0} , {"open":0} ,{"open":-5 } ,
{"open":35 } , {"open":0} ,{"open":0 },{"open":0 } ,{"open":-6 },
{"open":60},{"open":24},{"open":0},{"open":0},{"open":0},
{"open":0},{"open":0},{"open":0},{"open":0},{"open":46},
{"open":-9},{"open":28},{"open":9},{"open":-45},
{"open":-160},{"open":11} ]
As you got the hashmap, iterate the map like this:
Map<String,String> data = MapUtil.newHashMap();
JSONArray jsonArray = new JSONArray();
for (Map.Entry<String, String> entry : data.entrySet()) {
Map<String,String> json = MapUtil.newHashMap();
json.put("open", entry.getValue());
jsonArray.add(json);
}
return jsonArray;
Hi I am trying to read a very complicated nested Json of following structure and need to fetch all label values and store in a list. I tried many approaches but I am not successful .Can you please help me on this.I have tried below code .but not able to fetch the details
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
if (key.toString().equalsIgnoreCase("labels")) {
Strin val = json.get(key).toString();
System.out.println(val);
}
}
{
"expand":"schema,names",
"total":142,
"issues":[
{
"id":"10220951",
"fields":{
"labels": [
"Test"
]
}}{
"id":"10220952",
"fields":{
"labels": [
"Test2"
]
}}
I have 2 solutions, you can choose one of them.
1.Use JsonPath of Rest-Assured
import io.restassured.path.json.JsonPath;
List<List<String>> allLabels = JsonPath.from(jsonString).getList("issues.fields.labels");
List<String> labels = allLabels.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(labels);
//[Test, Test2]
2.Use JsonPath of jayway
import com.jayway.jsonpath.JsonPath;
List<List<String>> allLabels = JsonPath.read(res, "$..labels");
List<String> labels = allLabels.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(labels);
//[Test, Test2]
I have a JSON Object which I created from a .json file which looks like the follownig:
{
"key1": {
"key2": "value2",
"key3": "value3",
}
}
To generate the JSON-Object I use:
JSONObject newJSON = new JSONObject(content);
What I want to do, is to generate a String array, which contains all keys of the existing JSONObject, to easily access them.
JSONObject implements the Map interface, so you can use the same way you'd use for Map to generate the list of keys. In particular, you can use the .keySet() or .entrySet() method.
For example (adapted from here):
JSONObject jsonObj = ...;
List<String> l = new ArrayList<String>(jsonObj.keySet());
You could iterate through the keys.
JSONObject newUserJSON = new JSONObject(content);
ArrayList<String> keys = new ArrayList<>();
String key;
for (Iterator<String> it = newUserJSON.keys(); it.hasNext(); ) {
key = it.next();
keys.add(key);
}
And also you need to take care of nested json Object for each key.
Answer to this question is already available in another SO thread: Convert string to JSON array
Here's the equivalent for your use case:
JSONObject jsnobject = new JSONObject(content);
JSONArray jsonArray = jsnobject.getJSONArray("key1");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
I am struggling to fit in a jsonArray inside a json object (through java code).. please help me out.
My Input JsonObject is :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W"
}
}
I will have to read "imageURL" property from this JSONObject and append its variants to the same json object (image variants will be in SortedSet data structure).
Sample O/P 1 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
"http:example.com/imageResource_variant1.jpg",
"http:example.com/imageResource_variant2.jpg"
]
}
}
Sample O/P 2 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
}
}
The logic i tried to get sample output 2 is some what like below,
// productDetail is the give input JSONObject
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
product.append("variants", imageUrlsArray);
When i tried to print the productDetail JSON object after executing above logic
System.out.println(productDetail.toString());
I observed the following output :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
]
}
}
If you notice, It's coming up like Array of arrays (extra [ ] for "variants"),
Please help me in understanding Where my logic is going wrong.
And also, Please help me getting the First sample out put.
Appreciate quick response..
Thanks,
Rohit.
First sample can be archivable as simple as this:
JSONObject product = productDetail.optJSONObject("products");
JSONArray imageUrlsArray = new JSONArray();
imageUrlsArray.put(0, "http:example.com/imageResource_variant1.jpg");
imageUrlsArray.put(1, "http:example.com/imageResource_variant2.jpg");
product.append("variants", imageUrlsArray);
Try using put instead of append:
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
-product.append("variants", imageUrlsArray);
+product.put("variants", imageUrlsArray);
From the docs:
Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated with a JSONArray, then the value parameter is appended to it.
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