How to create multiple JSON objects via for loop [duplicate] - java

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 5 years ago.
I need to create variable amount of JSON objects and JSON arrays based on the result set from a database query. The JSON format looks very similar to the following which is used for a google chart.
{
“cols”: [
{"id":"","label":"year","type":"string"},
{"id":"","label":"sales","type":"number"},
{"id":"","label":"expenses","type":"number"}
],
“rows”: [
{"c":[{"v":"2001"},{"v":3},{"v":5}]},
{“c”:[{"v":"2002"},{"v":5},{"v":10}]},
{“c”:[{"v":"2003"},{"v":6},{"v":4}]},
{“c”:[{"v":"2004"},{"v":8},{"v":32}]},
{“c”:[{"v":"2005"},{"v":3},{"v":56}]}
]
}
My question is, and I feel as though this should be a simple answer, how do I create multiple JSON objects with unique names in a for loop? My attempt:
for(int i=0;i<10;i++) {
JSONObject "tempName"+i = new JSONObject();
}

Java variable names cannot be constructed dynamically.
I don't know how no one has answered this yet but here you are.
JSONObject objects = new JSONObject[10];
for(int i = 0 ; i < objects.length ; i++) {
objects[i] = new JSONObject();
}
JSONObject o = objects[2]; // get the third one
Arrays are not dynamically resizable. You should use an appropriate List implementation if you need such behavior. If you want to access the elements by name, you can also use a Map.
Map<String, JSONObject> map = new HashMap<>();
for(int i = 0 ; i < 10 ; i++) {
map.put("tempName" + i, new JSONObject());
}
JSONObject o = map.get("tempName3"); // get the 4th created (hashmaps don't have an ordering though)

JSONArray arr = new JSONArray();
HashMap<String, JSONObject> map = new HashMap<String, JSONObject>();
for(int i = 0 ; i < 10 ; i++) {
JSONObject json=new JSONObject();
json.put("id",i);
json.put("firstName","abc"+i);
map.put("json" + i, json);
arr.put(map.get("json" + i));
}
System.println("The json string is " + arr.toString());
OutPut is
The json string is
[
{"id":0,"firstName":"abc0"},
{"id":1,"firstName":"abc1"},
{"id":2,"firstName":"abc2"},
{"id":3,"firstName":"abc3"},
{"id":4,"firstName":"abc4"}
]

import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;
/**
* Some solution for write files from different folders to JSON
* #author Dmytro Melnychuk
*/
public class ParseFilesToJson {
public static void main(String[] args) {
List<String> folderNames = Arrays.asList("dwg", "eta-en", "eta-pl", "inst", "prod", "tds-en", "tds-pl");
folderNames.forEach(it -> {
writeIntoFile(it);
});
}
private static void writeIntoFile(String folderName) {
File directory = new File("C:\\Users\\mel\\AppData\\Roaming\\data\\" + folderName);
File[] directories = directory.listFiles();
JSONArray array = new JSONArray();
JSONObject json;
for (int i = 0; i < directories.length; i++) {
json = new JSONObject();
json.put("name", directories[i].getName());
json.put("version", 1);
array.put(json);
}
try (Writer file = new FileWriter("d:\\" + folderName + ".json")) {
array.write(file, 2, 0);
} catch (IOException e) {
}
}
}
Solution has prepared for people with Java 7 and less :)

Related

Convert JSON into List of Object property (Java)

I have simple json which looks like this :
[
{
"id":"0",
"name":"Bob",
"place":"Colorado",
},
{
"id":"1",
"name":"John",
"place":"Chicago",
},
{
"id":"2",
"name":"Marry",
"place":"Miami",
}
]
What I want is using Java to create list of strings (List<String>) that contains all 'names'. I have some experience using Gson and I think about something like:
Gson gson = new Gson();
String[] stringArray= gson.fromJson(jsonString, " ".class);
The problem with this method is that I should create some POJO class which I didn`t in this case. Is it any way I can achieve it without creating separate class with this 'name' property ?
Using Jackson to parse, and Java 8 Streams API for extracting only the name field; the following may help you:
// Your string
jsonString = "[{ \"id\":\"0\", \"name\":\"Bob\", \"place\":\"Colorado\" }, { \"id\":\"1\", \"name\":\"John\", \"place\":\"Chicago\"}, { \"id\":\"2\", \"name\":\"Marry\", \"place\":\"Miami\" }]";
// using Jackson to parse
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getTypeFactory();
List<MyInfo> myObjectList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, MyInfo.class));
// Java 8 Collections
List<String> nameList = myObjectList.stream().map(MyInfo::getName).collect(Collectors.toList());
Beware, it implies the usage of a MyInfo class representing your a Java class in which Json objects of yours would fit in.
You can use JSONArray to get value from key 'name'. Like this:
JSONArray jSONArray = new JSONArray(yourJson);
List<String> list = new ArrayList<>();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject object = (JSONObject) jSONArray.get(i);
String value = object.getString("name");
System.out.println(value);
list.add(value);
}
You may try the following code snippet,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
List<String> ls = new ArrayList<String>();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONParser jsonParse = new JSONParser();
String str = "[{\"id\": \"0\",\"name\": \"Bob\",\"place\": \"Colorado\"},"
+ "{\"id\": \"1\",\"name\": \"John\",\"place\": \"Chicago\"},"
+ "{\"id\": \"2\",\"name\": \"Marry\",\"place\": \"Miami\"}]";
try {
jsonArr= (JSONArray) jsonParse.parse(str); //parsing the JSONArray
if(jsonArr!=null){
int arrayLength =jsonArr.size(); //size is 3 here
for(int i=0;i<arrayLength;i++){
jsonObj = (JSONObject) jsonParse.parse(jsonArr.get(i).toString());
ls.add(jsonObj.get("name").toString()); //as we need only value of name into the list
}
System.out.println(ls);
}
} catch (ParseException e) {
e.printStackTrace();
}catch(Exception e1){
e1.printStackTrace();
}
As you have array, use JSONArray and used jsonParse to avoid any parsing error.
I have used json-simple API to acheive the above.

ArraysList as JSON

I wrote the below code in order for me to output a ArrayList as JSON. When I ran the code I get the output as shown below:
{uniteids:=[{"UniteId:":"gsheetyr","Message:":" The given user is already a member of the given DL.,"},{"UniteId:":"spokuri ","Message:":" The given user is already a member of the given DL.,"}]}
But, I wanted the output to be in the below format. Can you please let me know what changes I need to make to my code?
{"uniteids":[{"UniteId:":"gsheetyr","Message:":" The given user is already a member of the given DL.,"},{"UniteId:":"spokuri ","Message:":" The given user is already a member of the given DL.,"}]}
Code:
package com.uniteid.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
public class JsonResponse {
public static void main(String[] args) {
List<String> retStatus = new ArrayList<String>();
Map<String, String> stat = new HashMap<String, String>();
String jsonInString = "NORESPONSE";
String jsonInString2 = "";
Map<String, String> uniteidshashMap = new HashMap<String, String>();
JSONArray ja = new JSONArray();
retStatus.add("gsheetyr: The given user is already a member of the given DL.,");
retStatus.add("spokuri : The given user is already a member of the given DL.,");
if (retStatus.size() > 0) {
for (int i = 0; i < retStatus.size(); i++) {
String splited[] = retStatus.get(i).split("\\:");
stat.put("UniteId:", splited[0]);
stat.put("Message:",splited[1]);
ja.put(stat);
System.out.println(ja);
}
jsonInString = ja.toString();
uniteidshashMap.put("uniteids:", jsonInString);
jsonInString2 = uniteidshashMap.toString();
System.out.println(jsonInString2);
}
}
}
Try this
JSONArray arrayHolder = new JSONArray();
if (retStatus.size() > 0) {
for (int i = 0; i < retStatus.size(); i++) {
String splited[] = retStatus.get(i).split("\\:");
JSONObject innerObj = new JSONObject();
innerObj.put("UniteId:", splited[0]);
innerObj.put("Message:",splited[1]);
arrayHolder.put(innerObj);
}
JSONObject finalObject = new JSONObject();
finalObject.put("uniteids:", arrayHolder);
System.out.println(finalObject.toString());
}
I believe if you wrap your uniteidshashMap object inside a JsonArray and call toString() on that instead, you'll get a better result.

How to convert a string to JSONArray

I am hitting an api and getting a string response. The response is something like this
"["VU","Vanuatu",["Pacific/Efate","(GMT+11:00) Efate"],"VN","Vietnam",["Asia/Saigon","(GMT+07:00) Hanoi"]]"
And i want to convert this string into a json array of below type
[{"id":"VN","name":"Vanuatu","timezones":[{"id":Pacific/Efate,"name":"(GMT+11:00) Efate}]},"id":"VN","name":"Vietnam",[{"id":"Asia/Saigon","name":"(GMT+07:00) Hanoi"}]]
Can someone help
Looking at your String response, I've created a regular expression that will create four groups out of your response.
DEMO
Assuming that your output would come always in groups of four (i.e., id, name and timezones_id, timezones_name), this regular expression, would extract 4 groups out of the input string that you've provided:
Regex:
"([^"]*)",\s*"([^"]*)",\s*\["([^"]*)",\s*"([^"]*)"\]
Matches
Match 1
Full match 1-56 `"VU", "Vanuatu", ["Pacific/Efate", "(GMT+11:00) Efate"]`
Group 1. 2-4 `VU`
Group 2. 8-15 `Vanuatu`
Group 3. 20-33 `Pacific/Efate`
Group 4. 37-54 `(GMT+11:00) Efate`
Match 2
Full match 58-111 `"VN", "Vietnam", ["Asia/Saigon", "(GMT+07:00) Hanoi"]`
Group 1. 59-61 `VN`
Group 2. 65-72 `Vietnam`
Group 3. 77-88 `Asia/Saigon`
Group 4. 92-109 `(GMT+07:00) Hanoi`
 
Now once you've extracted these 4 groups, You can simply add appropriately in ArrayList and List and create JSONArray out of those lists.
The following program is self-explanatory with the inputs and outputs.
Input
["VU","Vanuatu",["Pacific/Efate","(GMT+11:00) Efate"],"VN","Vietnam",["Asia/Saigon","(GMT+07:00) Hanoi"]]
Output
[{"timezones":{"name":"(GMT+11:00) Efate","id":"Pacific/Efate"},"name":"Vanuatu","id":"VU"},{"timezones":{"name":"(GMT+07:00) Hanoi","id":"Asia/Saigon"},"name":"Vietnam","id":"VN"}]
Formatted Output
[{
"id" : "VU",
"name" : "Vanuatu",
"timezones" : {
"name" : "(GMT+11:00) Efate",
"id" : "Pacific/Efate"
}
}, {
"id" : "VN",
"name" : "Vietnam",
"timezones" : {
"name" : "(GMT+07:00) Hanoi",
"id" : "Asia/Saigon"
}
}
]
Code
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
public class Test
{
public static void main(String[] args) throws IOException, JSONException {
String serverResponse = "[\"VU\", \"Vanuatu\", [\"Pacific/Efate\", \"(GMT+11:00) Efate\"], \"VN\", \"Vietnam\", [\"Asia/Saigon\", \"(GMT+07:00) Hanoi\"]]";
Map<String, Object> prop, innerProp;
List<Object> arr = new ArrayList<>(), obj;
String pattern = "\"([^\"]*)\",\\s*\"([^\"]*)\",\\s*\\[\"([^\"]*)\",\\s*\"([^\"]*)\"\\]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(serverResponse);
while (m.find()) {
prop = new HashMap<>();
prop.put("id", m.group(1));
prop.put("name", m.group(2));
innerProp = new HashMap<>();
innerProp.put("id", m.group(3));
innerProp.put("name", m.group(4));
prop.put("timezones", innerProp);
arr.add(prop);
}
JSONArray jsonArray = new JSONArray(arr);
System.out.println(jsonArray.toString());
}
}
An option you have is to first create a JSONArray off of the string, and then read elements 3 by 3 from that array to create your output:
public static void main(String[] args) {
String input = "[\"VU\",\"Vanuatu\",[\"Pacific/Efate\",\"(GMT+11:00) Efate\"],\"VN\",\"Vietnam\",[\"Asia/Saigon\",\"(GMT+07:00) Hanoi\"]]";
JSONArray inputArray = new JSONArray(input);
JSONArray outputArray = new JSONArray();
for (int i = 0; i < inputArray.length(); i += 3) {
JSONObject obj = readCountry(inputArray, i);
outputArray.put(obj);
}
System.out.println(outputArray);
}
private static JSONObject readCountry(JSONArray array, int index) {
JSONObject country = new JSONObject();
country.put("id", array.getString(index));
country.put("name", array.getString(index + 1));
country.put("timezones", readTimeZones(array.getJSONArray(index + 2)));
return country;
}
private static JSONArray readTimeZones(JSONArray array) {
JSONArray timezones = new JSONArray();
JSONObject timezone = new JSONObject();
timezone.put("id", array.getString(0));
timezone.put("name", array.getString(1));
timezones.put(timezone);
return timezones;
}
You may add some error handling to fail gracefully or even recover with best effort if the input doesn't match.

Create list of java objects from json

I have following json which i need to convert into list of java objects.
{
"model":[
{
"syscall_1":"execve",
"syscall_2":"brk"
},
{
"syscall_1":"brk",
"syscall_2":"access"
},
{
"syscall_1":"access",
"syscall_2":"mmap"
},
{
"syscall_1":"mmap",
"syscall_2":"access"
}
]
}
I am using gson and its TypeToken>(){}.getType() API ,however I am bit confused about how my objects should look corresponding to input json.
How can I use TypeToken in this scenario?
Another option (not using the type token, but still achieves what you want) would be to parse the entire json object, then access the model array like so:
import com.google.gson.Gson;
import java.util.List;
public class TestMe {
public static void main(String[] args) {
String jsonSt2 = "{\"model\":[{\"syscall_1\":\"execve\",\"syscall_2\":\"brk\"},{\"syscall_1\":\"brk\",\"syscall_2\":\"access\"},{\"syscall_1\":\"access\",\"syscall_2\":\"mmap\"},{\"syscall_1\":\"mmap\",\"syscall_2\":\"access\"}]}";
System.out.println("your json: " + jsonSt2);
ModelObject object = new Gson().fromJson(jsonSt2, ModelObject.class);
System.out.println("Created Model object, array size is " + object.model.size());
for (ModelItem mi : object.model) {
System.out.println(mi.syscall_1 + " " + mi.syscall_2);
}
}
}
class ModelObject {
List<ModelItem> model;
}
class ModelItem {
String syscall_1;
String syscall_2;
}
Output
Created Model object, array size is 4
execve brk
brk access
access mmap
mmap access
mmap access
If you can use org.json to parse and construct list objects, you can try this.
String jsonSt2 = "{\"model\":[{\"syscall_1\":\"execve\",\"syscall_2\":\"brk\"},{\"syscall_1\":\"brk\",\"syscall_2\":\"access\"},{\"syscall_1\":\"access\",\"syscall_2\":\"mmap\"},{\"syscall_1\":\"mmap\",\"syscall_2\":\"access\"}]}";
List<Model> models = new ArrayList<>();
JSONObject jsonModelObject = new org.json.JSONObject(jsonSt2);
Object modelObject = jsonModelObject.get("model");
if (modelObject instanceof JSONArray) {
JSONArray itemsArray =(JSONArray) modelObject;
for (int index = 0; index < itemsArray.length(); index++) {
Model model = new Model();
JSONObject modelItereative = (JSONObject) itemsArray.get(index);
model.setSyscall_1(modelItereative.getString("syscall_1"));
model.setSyscall_2(modelItereative.getString("syscall_1"));
models.add(model);
}
}else if(modelObject instanceof JSONObject){
Model model = new Model();
JSONObject modelItereative = (JSONObject) modelObject;
model.setSyscall_1(modelItereative.getString("syscall_1"));
model.setSyscall_2(modelItereative.getString("syscall_1"));
models.add(model);
}
for(Model d22:models){
System.out.println(d22.getSyscall_1() + " " + d22.getSyscall_2());
}

Parsing JSON array

I'm using GSON for parsing JSON response.
Unfortunately the WebApi on the server has quite untypical JSON objects.
I need to parse Attachments array from this JSON (there can be more attachments):
{"htmlMessage":"text","Attachments":{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg","contentDisposition":"attachment","size":86070}}}
Where 8216096_0 is attachments id.
I can't do it with Gson (or I don't know how) so I'm trying to do it with JSONObjects:
// parse attachments
JSONObject attachmentsJson = result.getJSONObject("Attachments");
Then I have one JSONObject with an array of attachments, but I don't know how to get them to the ArrayList from JSONObject because the key value isn't static but generated id..
Thank you
//EDIT:
Thanks to all guys for helping! My final solution looks like this especially thanks to #Jessie A. Morris and his final answer!
List<AttachmentModel> attachmentsList = new ArrayList<AttachmentModel>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
AttachmentModel attachmentModel = new AttachmentModel();
attachmentModel = gson.fromJson(attachment.getValue().getAsJsonObject().toString(), AttachmentModel.class);;
attachmentModel.setmUid(attachment.getKey());
attachmentsList.add(attachmentModel);
}
Okay, I've changed my example a little bit and am certain that this does work correctly (I just tested it):
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by jessie on 14-07-09.
*/
public class TestGson {
private static String JSON = "{\"htmlMessage\":\"text\",\"Attachments\":{\"8216096_0\":{\"content\":null,\"filename\":\"plk.jpg\",\"contentType\":\"image/jpeg\",\"contentDisposition\":\"attachment\",\"size\":86070}}}\n";
public static void main(String[] args) {
JsonObject json = new JsonParser().parse(JSON).getAsJsonObject();
JsonObject attachments = json.getAsJsonObject("Attachments");
List<JsonObject> attachmentsList = new ArrayList<JsonObject>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
attachmentsList.add(attachment.getValue().getAsJsonObject());
}
System.out.println("attachmentsList at the end? " + attachmentsList);
}
}
I'm not completely sure if this really works:
final Map<String,JSONObject> attachmentsJson = (Map<String,JSONObject>) jsonArray.getJSONObject("Attachments");
for(String attachmentId : attachmentsJson.keySet()) {
final JSONObject attachmentJson = attachmentsJson.get(attachmentId);
}
The "Attachments" obj in your example is not an array.
Json arrays are denoted by [....].
"Attachments" is a Json object holding an inner object called "8216096_0".
so to get the inner values do as follows:
JSONObject attachmentsJson = result.getJSONObject("Attachments");
JSONObject inner = attachmentsJson.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
Finally, and for example sake, I will add the code for processing a (real) Json array:
{"htmlMessage":"text",
"Attachments":[{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
{"8216096_1":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
]
}
It will go like this:
JSONArray attachmentsJson = result.getJSONObject("Attachments");
int len = attachmentsJson.length();
for (int i = 0; i < len; i++) {
JSONObject elem = attachmentsJson.getJSONObject(i); // <------ get array element
JSONObject inner = elem.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
}
..Or similar, depending on your Json's exact format.

Categories

Resources