Parse Json inside servlet - java

I have this array list in java
[ {"pname":"7", "qty":"222"},
{"pname":"8", "qty":"5"},
{"pname":"9", "qty":"60"} ]
I can access the first index which is object, how can I access the first element inside the first object which is "pname" key in java syntax. Please give me sample codes. Thanks.
I tried:
mylist.get(0)
but it only gives me the first object. I don't know how to access the first index inside the object.
here is my whole code from getting the data to parse it into json array and convert to array list
String data = request.getParameter("data");
JSONArray jsonArray = new JSONArray(data);
ArrayList<String> mylist = new ArrayList<String>();
JSONArray this_is_jsonArray = (JSONArray)jsonArray;
if (jsonArray == null) {
System.out.println("json is empty");
}
else
{
int length = this_is_jsonArray.length();
for (int i=0;i<length;i++){
mylist.add(this_is_jsonArray.get(i).toString());
}
}
output.append(mylist);
Basically I'm trying to do a function similar output to this mylist[0].pname in javascript. the expected output all in all is to save those pnames and qtys to a variable for me to able to send each value to the database

In order to write a proper answer you need to be very clear about the input and output you have and you expect.
I don't understand why you want to create a parallel data structure instead of using the parsed JSON but from what I read in comments I think that you need to change the structure of your ArrayList content in order to obtain the result you want to achieve.
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"9\", \"qty\":\"60\"} ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.put("pname", jsonObject.getString("pname"));
item.put("qty", jsonObject.getString("qty"));
mylist.add(item);
}
}
System.out.println(mylist);

First thing to consider is JSON object is not ordered.The first object can be pname or qty, in successive request. To access the fields, give field name as an associative array.
JSONArray jsonArray = new JSONArray(data);
ArrayList<String> mylist = new ArrayList<String>();
JSONArray this_is_jsonArray = (JSONArray)jsonArray;
if (jsonArray == null) {
System.out.println("json is empty");
}
else
{
int length = this_is_jsonArray.length();
for (int i=0;i<length;i++){
// Just this line is modified
mylist.add(this_is_jsonArray.getJSONObject(i).getString("pname").toString());
}
}

Related

How to display multiple JSON Object simultaneously in postman?

public String doStock(JsonObject SymbolName) throws Exception {
JSONObject obj2 = new JSONObject(SymbolName);
JSONArray jsonArray = (JSONArray) obj2.get("SymbolName");
JSONObject obj3 = new JSONObject();
Object obj = null;
System.out.println("");
System.out.println("Symbol Name: ");
//Iterating the contents of the array
for(int i = 0; i < jsonArray.length(); i++){
obj = jsonArray.get(i);
System.out.println(obj);
obj3=checkStock(obj.toString());
}
return obj3.toString();
}
my post request : {"SymbolName":["ODP","ACC"]} in this only the details regarding ACC is returning to postman but in console both are showing, I want to display the json object regarding both ODP ans ACC. How to do this?
The issue is not with PostMan, but with your response object.
You will need to create a wrapper method which will compose the different "SymbolName" return objects into a new object.
Based on the code you have shown, I understand that you need to iterate through each of your symbolname using a method named doStock(), inside which you run the checkStock(symbolname) method for each symbolname, append the return object of the checkStock method into an array/List and finally when all the symbolnames are processed, return the array/List.
This array will have all your json objects.
In your code obj3 is getting over written in the loop and that is why you only get to see one object in postman, which will be the last obj3 you return.
Please see the modified code below:
public List doStock(JsonObject SymbolName) throws Exception {
JSONObject obj2 = new JSONObject(SymbolName);
JSONArray jsonArray = (JSONArray) obj2.get("SymbolName");
JSONObject obj3 = new JSONObject();
List returnList = new ArrayList()
Object obj = null;
System.out.println("");
System.out.println("Symbol Name: ");
//Iterating the contents of the array
for(int i = 0; i < jsonArray.length(); i++){
obj = jsonArray.get(i);
System.out.println(obj);
obj3=checkStock(obj);
returnList.add(obj3)
}
return returnList;
}
I had this issue this morning. the reason was inconsistent type of JSON classes we've used throughout our app.

Converting JSONarray to ArrayList with Java

Hi i have simply problem, but i can find solution. If somebody can show to me solution.
...
(Unirest) HttpResponse<String> paluuREST = AbaXapi.HttpResponse(aString);
enter bring outside to me long Json Array:
So i put this inside Arraylist and short diffrent values...
"{\"body\":[{\"id\":\"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97\",\"name\":\"DFB-572\",\"imei\":13226005525791,\"vehicle_params\":{\"vin\":null,\"make\":null,\"model\":null,\"plate_number\":null}}]}"
Here is java code:
JSONObject jsonObject = new JSONObject(paluuREST);
System.out.println(jsonObject);
JSONArray jsonArray = jsonObject.getJSONArray("body");
ArrayList<Object> listdata = new ArrayList<Object>();
for (int i=0;i<jsonArray.length();i++){
//Adding each element of JSON array into ArrayList
listdata.add(jsonArray.get(i));
}
System.out.println("Each element of ArrayList");
for(int i=0; i<listdata.size(); i++) {
//Printing each element of ArrayList
System.out.println(listdata.get(i));
}
Error Message:
Exception in thread "main" org.json.JSONException: JSONObject["body"] is not a JSONArray.
at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2628)
So how can be? How i need to change code, thanks for your help.
Please be more carefull in the formulation of the question, if everything is brought to the right, then there are no problems.
public static void main(String[] args) throws Exception {
String s = "{\"body\":[{\"id\":\"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97\",\"name\":\"DFB-572\",\"imei\":13226005525791,\"vehicle_params\":{\"vin\":null,\"make\":null,\"model\":null,\"plate_number\":null}}]}";
JSONObject obj = new JSONObject(s);
JSONArray body = obj.getJSONArray("body");
System.out.println(body);
ArrayList<Object> objects = new ArrayList<>();
for (Object o : body) {
objects.add(o);
}
System.out.println("objects = " + objects);
}
used org.json lib

Java JSONObject getJsonArray Blank String

I have some JSON that is returned as follows:
[{"on_arrival_inst":"Ok","order_inst":"Ok","finished_inst":"Ok"},{"on_arrival_inst":"Arrive","order_inst":"Order","finished_inst":"Finished"}]
I am trying to split these into two arrays and get the strings out as follows:
jsonResultsObject = new JSONObject(result);
jsonArray = jsonResultsObject.getJSONArray("");
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
However the code never goes into the loop, as the array is not getting populated from the JSONObject?
your result is JSONArray not JSONObject. That's why you must convert it to array not to object.
use
jsonResultsArray = new JSONArray(result);
instead of
jsonResultsObject = new JSONObject(result);
and the full code will be
jsonResultsArray = new JSONArray(result);
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonResultsArray.length()){
JSONObject JO = jsonResultsArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
#BigJimmyJones
The fact of that the code does not enter the loop is just because your JSONArray does not have a key named "" but it contains JSONObjects instead. Objects and arrays in JSON have different annotations. See: JSON Reference Website
So your code should be :
jsonResultsObject = new JSONObject(result);
String onArrive, onReady, onFinished;
for (int i=0;i<jsonArray.length();i++){
JSONObject JO = jsonArray.getJSONObject(i);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
}
And also ensure that your code is inside a try - catch block to catch JSONException

Add the string from the loop in the ArrayList<String>

I'm parsing a jsonData and getting the video_url from it. What my requirements is to add the video_url inside the ArrayList. I've tried everything and getting the result as this in my logCat :
E/VIDEO URL: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FJIMyHoviVideo.mp4?alt=media&token=c103543e-31f0-4682-9b44-09d679c76699]
E/VIDEO URL: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FBMMyHoviVideo.mp4?alt=media&token=9bcf98a1-dad1-4f63-864f-7559ef1d49c1]
Now here you can clearly see that the video_url is coming in this format what I want a single ArrayList containing both the url.
This is the code I've done to print the desired result but it is not coming fine :
private void jsonParsingVideoData(String projectVideos, String projectId) throws JSONException{
JSONArray jsonArray = new JSONArray(projectVideos);
ArrayList<String> video_url = null;
for(int i=0; i< jsonArray.length() ; i++){
JSONObject jObject = jsonArray.getJSONObject(i);
video_url = new ArrayList<>(Arrays.asList(jObject.getString("video_url")));
Log.e("VIDEO URL", video_url.toString());
}
}
I've tried in this way also but it failed, only one output is there if I'm doing in this way out of the loop.
for( String string : video_url){
ArrayList<String> string1 = new ArrayList<>();
string.add(string);
Log.e("LOGS", string1.toString());
}
for the above code the output is coming only one and in this format :
E/LOGS: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FBMMyHoviVideo.mp4?alt=media&token=9bcf98a1-dad1-4f63-864f-7559ef1d49c1]
Please help me with this, I've tried a lot. Thanks.
You are creating a new ArrayList every loop iteration. You should use add instead!
private void jsonParsingVideoData(String projectVideos, String projectId) throws JSONException{
JSONArray jsonArray = new JSONArray(projectVideos);
ArrayList<String> video_urls = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jObject = jsonArray.getJSONObject(i);
video_urls.add(jObject.getString("video_url"));
}
}

How to parse Json using Java?

I want to parse a json object in java.The json file is {"l1":"1","l2":"0","f1":"0","connected":"0","all":"0"}
i am trying to write a java program to print above json as
l1=1
l2=0
f1=0
connected=0
all=0
The number of entries in the json file can be increased, so i have to loop through the json and print all data. This is what i've done so far.
public class main {
public static void main(String[] args){
try{
URL url = new URL("http://localhost/switch.json");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject root = new JSONObject(tokener);
JSONArray jsonArray = root.names();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
System.out.println(jsonArray.get(i).toString());
}
}
}catch (Exception e) {
e.printStackTrace();
System.out.println("Error Occured");
}
}
}
the above program can only print the first item of each array. But i am trying get the result i mentioned in the beginning. Can anybody help ??
It is simple JSON object, not an array. You need to iterate through keys and print data:
JSONObject root = new JSONObject(tokener);
Iterator<?> keys = root.keys();
while(keys.hasNext()){
String key = (String)keys.next();
System.out.println(key + "=" + root.getString(key));
}
Please note that above solution prints keys in a random order, due to usage of HashMap internally. Please refer to this SO question describing this behavior.
Your JSON file does not contain an array - it contains an object.
JSON arrays are enclosed in [] brackets; JSON objects are enclosed in {} brackets.
[1, 2, 3] // array
{ one:1, two:2, three:3 } // object
Your code currently extracts the names from this object, then prints those out:
JSONObject root = new JSONObject(tokener);
JSONArray jsonArray = root.names();
Instead of looping over just the names, you need to use the names (keys) to extract each value from the object:
JSONObject root = new JSONObject(tokener);
for (Iterator<?> keys= root.keys(); keys.hasNext();){
System.out.println(key + "=" + root.get(keys.next()));
}
Note that the entries will not print out in any particular order, because JSON objects are not ordered:
An object is an unordered set of name/value pairs -- http://json.org/
See also the documentation for the JSONObject class.

Categories

Resources