ArraysList as JSON - java

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.

Related

Avoiding duplicates while adding jsonobjects into the jsonarray using java

I have a list of objects and am converting into JSONArray. Am iterating over the JSONObjects and making an array of JSONObjects.
Now, i want to avoid duplicates objects to get insert into the JSONArray.
Please find my java code below.
JSONArray responseArray1 = new JSONArray();
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String attr_label = jsonObj.optString("attr_label");
if(StringUtils.equalsIgnoreCase(attr_label, "long_description")) {
long_description = jsonObj.optString("value");
}
else if(StringUtils.equalsIgnoreCase(attr_label, "description")) {
description = jsonObj.optString("value");
}
responseObj.put("id", jsonObj.opt("id")); // i will get duplicate id
responseObj.put("code", jsonObj.opt("code")); // i will get duplicate code
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray1.put(responseObj);
}
}
Please find my actual jsonArray :
[
{
"code":"xyaz",
"attr_label":"long_description",
"id":"12717",
"value":"Command Module"
},
{
"code":"xyaz",
"attr_label":"description",
"id":"12717",
"value":"Set Point Adjustment"
},
]
Am expecting like the below jsonArray :
[
{
"code":"xyaz",
"id":"12717",
"long_description":"Command Module"
"description" : "Set Point Adjustment"
}
]
Update :
I have tried with the below code to avoid duplicate insertion of id & code field. but is not working properly. Its inserting duplicates also.
List<String> dummyList=new ArrayList<String>();
JSONArray responseArray2 = new JSONArray(itemList);
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String itemCode = jsonObj.optString("code");
String id = jsonObj.optString("id");
if(!dummyList.contains(itemCode) && !dummyList.contains(id) ) {
dummyList.add(String.valueOf(jsonObj.opt("id")));
dummyList.add(String.valueOf(jsonObj.opt("code")));
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray2.put(responseObj);
}
}
}
Make a temporary array list and add unique code in that arrayList and check if it already exists in arrayList then don't put this again
String code = jsonObj.opt("code");
if(!arrayList.contains(code))
{
arrayList.add(code);
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
}
use TreeSet and add Comparator to their constructor in which it compare the duplicate data of the object.
for example:-
Set<Sample> sampleSet=new TreeSet<>(new Sample());
where Sample Class look like:-
class Sample implements Camparator<Sample>{
private String name;
private String id;
//getter
//setter
#Override
public String compare(Sample o1,Sample o2){
return o1.getName.compareTo(o2.getName);
}
}
This will give a set of unique name entries.

read a string in JSON format in JAVA

I want to read a string as a JSON format(it doesn't have to be JSON, but it seems like JSON format) and represent it to a hashMap(key : Keyword, value : COUNT)
for example, assume I have a String.
String s ={"Welcome":1,"Hi":2,"Hello":1,"Jin":1};
Then, make it classification.(for Hashmap key --> word, value--> number). final result would be something like as below.
HashMap<String,String> result;
result.get("Jin"); // output : 1
result.get("Hi"); // output : 2
but my codes, it doesn't go with right way.
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
JSONArray array = new JSONArray();
array.add(obj);
System.out.println(array.get(0)); //output: {"Welcome":1,"Hi":2,"Hello":1,"Jin":1}
can it be possible with JSON? or should I split them one by one? (such as split them with "," first and ":" ... so on)
Please give me your kind advice.
Try with below code snippet.
public static void main(final String[] args) throws ParseException {
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONParser parser = new JSONParser();
HashMap<String, Long> obj = (HashMap<String, Long>) parser.parse(s);
for(String key : obj.keySet()) {
System.out.println("Key:" + key + " value:" + obj.get(key));
}
}
You can use org.json to fulfill your requirement.
E.g.
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONObject result = new JSONObject(s);
System.out.println(result.get("Jin")); // output : 1
System.out.println(result.get("Hi")); // output : 2
The easiest to achieve this is by using JACKSON parsers.
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(s, new TypeReference<HashMap<String, String>>() {
});
map.forEach((k, v) -> System.out.println("Key is " + k + " value is " + v));
Prints :
Key is Hi value is 2
Key is Hello value is 1
Key is Welcome value is 1
Key is Jin value is 1
Its a json object not an array...
try this one :
JSONObject jsonObj = new JSONObject(jsonString.toString());
Use Google JSON i.e gson library(2.6.2) and your problem will be solved.
Please have a look to the following code
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class StackOverFlowQuestionset {
public static void main(String[] args) {
String s ="{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
HashMap<String,String> result=new HashMap<String,String>();
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(s, JsonElement.class);
JsonObject jsonObject = jsonElement.getAsJsonObject();
Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
for(Entry<String, JsonElement> entry:jsonEntrySet){
result.put(entry.getKey(), entry.getValue().toString());
}
System.out.println(result.get("Jin"));
System.out.println(result.get("Welcome"));
System.out.println(result.get("Hi"));
}
}

Java MAP to JSON

First of all, I'm new to Java so please be kind with me :-).
I have a map and I want to parse into JSON Object:
private static final Map<String, Queue<String>> myMap = new HashMap<String, Queue<String>>();
My Key is the login (email) of a user.
I would like to create a JSON Object like this one :
{
Login1: {
itemOne: 'item one',
itemTwo: 'item two'
},
Login2: {
itemOne: 'item one',
itemTwo: 'item two'
}
}
I have tried it using JSONObject or ObjectMapper but it didn't worked. I'm looking for some tips / advices.
Thanks,
The way you have it now, parsing Map<String, Queue<String>> into valid JSON would mean that you'd get something like this:
{
queueOne: {
itemOne: 'item one',
itemTwo: 'item two'
},
queueTwo: {
itemOne: 'item one',
itemTwo: 'item two'
}
}
If there's only one queue, putting it in a map isn't necessary. If there's multiple you'll have to iterate over the Map, create a JSONArray from the Queue and then put a JSONObject with the String as key and Queue as value into a main JSONArray.
It's strange, but the key of your map is never used in your example.
Completed example would be:
{
"key":{
"item2":"SecondItemOnTheQueue",
"item1":"FirstItemOnTheQueue",
"item3":"ThirdItemOnTheQueue"
}
}
Java code below:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import org.json.JSONObject;
public class App {
public static void main(String[] args) {
Map<String, Queue<String>> map = new HashMap<String, Queue<String>>();
map.put("key", new LinkedList<String>(){{
add("FirstItemOnTheQueue");
add("SecondItemOnTheQueue");
add("ThirdItemOnTheQueue");
}});
System.out.println(generateFromMapOfQueues(map));
}
private static JSONObject generateFromMapOfQueues(Map<String, Queue<String>> map) {
JSONObject result = new JSONObject();
for(String key : map.keySet()){
JSONObject queueJson = new JSONObject();
int initSize = map.get(key).size();
for (int i = 0; i < initSize; i++) {
queueJson.append("item" + (i + 1), map.get(key).poll());
}
result.put(key, queueJson);
}
return result;
}
}
The map after completion will contain empty queues... That's the only problem.

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.

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

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 :)

Categories

Resources