issue in looping - java

I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.
output :
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
code :
public class MyFormToJSONConverter {
public JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
List<JSONArray> list = new ArrayList<JSONArray>();
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
formDetailsJson.put("desc",
form.get(i).getFormDescription());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
}
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
return responseDetailsJson;
}

Your problem is here:
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
will overwrite all of the previous values with the next value (a single JSON object). You want
responseDetailsJson.put("form", list);
You probably should also get rid of this:
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
That will give you:
{
"forms": [
[{ "form_id": "1", "form_name": "test1" }],
[{ "form_id": "2", "form_name": "test2" }]
]
}
All told, I think you want:
JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList
// instead of an ArrayList.
for (Form formInstance:form) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", formInstance.getId());
formDetailsJson.put("form_name", formInstance.getName());
formDetailsJson.put("desc",
formInstance.getFormDescription());
list.add(formDetailsJson);
}
responseDetailsJson.put("form", list);

JSON objects are essentially key/value pairs. In your code you are doing:
for (JSONArray json : list)
{
responseDetailsJson.put("form", json);
}
You're overwriting the same key each time.

Related

How to get key value of objects inside an array in Java

I am trying to get key and value of json array response. I want to map each key and get its value. Currently I am looping the result of my response.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray jsonArray = (JSONArray) map;
for (Object o : jsonArray) {
JSONObject json = new JSONObject((Map) o);
for (Object obj : json.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
Here is the list of objects inside an array
[
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10011618",
"email": "adrian.cabral#example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
},
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10003025",
"email": "dummy#example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
}
]
I keep getting this error.
java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class org.json.simple.JSONObject
Try to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray json = (JSONArray) map;
for (int i=0; i < json.length(); i++) {
JSONObject e = json.get(i);
System.out.println(e);
}
}
You are casting it wrong.
JSONObject json = (JSONObject) map;
This casting is wrong (JSONObject) map. it should be (JSONArray) map.
Next time before casing object, you perhaps want to check type of object like this.
System.out.println(map.getClass().getName());

Get the keys from JSON Array into a list without Jackson

I have an service that returns me an json object like the below
{
"header": {},
"title": {},
"terms": {
"data": {
"list": [
"string": 1,
"string1": 2,
"string2": 3
]
}
}
}
Now I need to get the keys of the list json array into a list. I have got the array into an object
List<String> allTerms = new ArrayList<String>();
String response = HttpRequest.get("http://myservice/get").body();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
JSONObject fieldObj = (JSONObject)jsonObject.get("terms");
JSONObject queryObj = (JSONObject)fieldObj.get("data");
JSONArray termsArr = (JSONArray) queryObj.get("list");
//iterate the termsarr and get the string,string1,string2 keys alone to allTerms list
Is there a more better way to do this? Im using json-simple and a custom http client
By using basic for loop
for(int i=0; i<termsArr.length(); i++) {
String[] arr = termsArr.getString(i).split("\"");
allTerms.add(arr[1]);
}

how to get an specific element inside a json [duplicate]

I'm just getting started with using json with java. I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:
{
"locations": {
"record": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
}
my code:
JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
I have access to the "record" JSONArray at this point, but am unsure as to how I'd get the "id" and "loc" values within a for loop. Sorry if this description isn't too clear, I'm a bit new to programming.
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:
JSONArray lineItems = jsonObject.getJSONArray("lineItems");
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String key = jsonLineItem.getString("key");
String value = jsonLineItem.getString("value");
...
}
Works great... :)
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.
import org.json.JSONArray;
import org.json.JSONObject;
#Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
jsonConfig.setRootClass( Integer.TYPE );
int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
In case it helps someone else,
I was able to convert to an array by doing something like this,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
((JSONArray) myJsonArray).toArray().length
HashMap regs = (HashMap) parser.parse(stringjson);
(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");

Java GSON - make array from String of json

I want to make an array of product objects from a json file which is currently a String.
{
"invoice": {
"products": {
"product": [
{
"name": "Food",
"price": "5.00"
},
{
"name": "Drink",
"price": "2.00"
}
]
},
"total": "7.00"
}
}
...
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("product");
the line below give me: java.lang.NullPointerException
for(JsonElement element: jsonArray) {
//do stuff
System.out.println(element);
}
some code goes here...
product = new Product(name, price);
List<Product> products = new ArrayList<Product>();
products.add(product);
You have to traverse the whole JSON string to get to the "product" part.
JsonArray jsonArray = jsonObject.get("invoice").getAsJsonObject().get("products").getAsJsonObject().get("product").getAsJsonArray();
I would recommend that you create a custom deserializer as described in the second answer to this question: How do I write a custom JSON deserializer for Gson? This will make it a lot cleaner, and let you handle improper JSON and make it easier in case your JSON ever changes.
I think you can use Gson library for this
You can find the project and the documentation at : https://github.com/google/gson/blob/master/README.md
try
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject invoice = parser.parse(jsonString).getAsJsonObject();
JsonObject products = invoice.getAsJsonObject("products");
JsonArray jsonArray = products.getAsJsonArray("product");

Class cast exception [JSONArray cannot be cast to org.json.simple.JSONObject]

I have a json file like this
[ {
"id":"serve-coffee",
"tags":[ {
"name": "#tag1", "line": 1
}
],
"description":"Coffee should not be served\n",
"name":"Serve coffee",
"keyword":"Feature",
"line":2,
"elements":[ {
"id": "serve-coffee;buy-last-coffee", "tags":[ {
"name": "#tag2", "line": 6
}
],
"description":"",
"name":"Buy last coffee",
"keyword":"Scenario",
"line":7,
"steps":[ {
"name": "there are 1 coffees left in the machine", "keyword": "Given ", "line": 8
}
,
{
"name": "I have deposited 1$", "keyword": "And ", "line": 9
}
],
"type":"scenario"
}
],
"uri":"src\/test\/resources\/traffic-remove-locations.feature"
}
]
Iam trying to convert the above json file to JSONObject.But am getting class cast exception "java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
code
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
// Read from File to String
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
Object object = parser.parse(new FileReader(fileName));
jsonObject = (JSONObject) object; // Getting classCast Exception here.
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
but when i changed the line jsonObject = (JSONObject) object; to JSONArray jsonArray = (JSONObject)object the exception disappears.
But if am casting to JSONArray then how can i get the values like id,tags and description from JSONArray.
please provide a suggestion guys
Your JSON file represents an array with one object in it. So if that were a Java data structure, you're effectively doing this:
int[] arr = {5};
int i = (int)arr;
This obviously doesn't work because you can't cast an array to a singular object. What you actually want to do it pull out the first element of the array. To continue the Java example, you want to do
int[] arr = {5};
int i = (int)arr[0];
With the JSON stuff, your parser.parse() call returns a JSONArray, not a JSONObject. So you'll need to do something like this:
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
JSONArray array = (JSONArray) parser.parse(new FileReader(fileName));
jsonObject = array.getJsonObject(0);
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
Try casting to JsonArray and then cast access the objects one by one with help of the index from the JSON array.
Object object = parser.parse(new FileReader(fileName));
JsonArray jsonArr = (JsonArray) object; // Getting c
jsonObject jsonObj = jsonArr.get(0); //use index to access like a list
I was also facing the same issue. I did the below changes to make it work.
Below is my sample JSON.
{
"routes": [{
"startTime": 1520319414,
"routeInfo": [{
"routePart": 0,
"transType": "WALK",
"transDetails": {
"startLoc": {
"lat": 28.6434862,
"lon": 77.22542659999999
}
}
}, {
"routePart": 1,
"transType": "BUS",
"transDetails": {
"routeNumber": "307-U",
"interStopDetails": [{
"seq": 1,
"name": "test1",
"loc": {
"lat": 28.64302,
"lon": 77.2260367
},
"eta": 1520319600
}
]
}
}
],
"totalTime": 5742
}
]
}
Solution to Parse:
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(FilepathDummy));
JSONArray jsonRoutes= (JSONArray) obj.get("routes"); //Gives Main JSoN
JSONObject routeJsonObject = (JSONObject) jsonRoutes.get(0); // Route Array into JSON
JSONArray routeInfoArray = (JSONArray) routeJsonObject.get("routeInfo"); // RouteInfo Array
Hope this solve your problem.

Categories

Resources