Converting JSONarray to ArrayList with Java - 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

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.

Parse Json inside servlet

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());
}
}

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"));
}
}

Java JSON/GSON - search all objects within an array and return match

I am returning an JSON array which contains many objects, I'm looking to be able to search the attributes in each object and then return the objects that meet this criteria.
I am able to return the JSON array but I'm having trouble on how to then search through the objects to match the attribute values to a given value.
Some example values from the array:
[
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384640123117E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483379834470379E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384639621985E9,"uID":"136199_3_10"}
]
I'm using the following code to return the array, which works as expected:
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray rootArr = root.getAsJsonArray();
The following block of code is what I'm using to search through an object for the given attribute value, this code works when only an object is returned but gives an error when the whole array is returned:
JsonObject rootObj = rootArr.getAsJsonObject();
for (String attribute : attributes) {
System.out.println(rootObj.get(attribute).getAsString());
}
It is giving the error:
java.lang.IllegalStateException: Not a JSON Object:
I've tried changing rootObj.get(attribute) to rootArr.get(attribute) but that returns the error:
incompatible types: java.lang.String cannot be converted to int
This is the method call:
method("136199", Arrays.asList("blobJson", "deviceMfg", "uID"));
Method declaration:
void method(String sensor, List<String> attributes)
The issue is that you're trying to treat JsonArray to JsonObject. Try the below code and see if it works for you. Point of interest for now is - JsonObject rootObj = rootArr.get(0).getAsJsonObject();
public static void main(String[] args) {
String json = "[{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384640123117E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483379834470379E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384639621985E9,\"uID\":\"136199_3_10\"}]";
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(json);
JsonArray rootArr = root.getAsJsonArray();
JsonObject rootObj = rootArr.get(0).getAsJsonObject();
rootObj.entrySet().forEach(entry -> System.out.println(entry.getKey()+": "+entry.getValue().getAsString()));
}
Here is what you can try
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("JSON Count", jsonArray.get(i).toString());
}
} catch (Exception e) {
}

Remove json object from json array

I've a JsonArray like:
"fields" : [
{
"name":"First Name",
"id":1
},
{
"name":"Middle Name",
"id":2
},
{
"name":"Last Name",
"id":3
}
]
I want to remove second JsonObject from above JsonArray. In order to do that I' wrote following code:
JsonArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(fieldsObject.getJsonObject(2));
But second line throws error: java.lang.UnsupportedOperationException
Is there any way, I can remove JsonObject from a JsonArray?
You can not remove element from JsonArray as it does not support remove() method:
private static final class JsonArrayImpl extends AbstractList<JsonValue> implements JsonArray {
And remove() method's implementation comes from AbstractList :
public E remove(int index) {
throw new UnsupportedOperationException();
}
Instead why don't you create a separate data strucure array or list to hold the objects that you want?
By the way, the purpose of using JsonArray is to load json data in object form that is why it supports read methods but does not support modifications on the loaded data structure.
May be Your JsonElement or JSONArray is null.
getJsonObject returns a JSONObject.
the remove method want int.
UnsupportedOperationException
if removing is not supported.
Try This :
JSONArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(int index);
OR
JSONArray result = new JSONArray();
for(int i=0;i<fieldsObject.length();i++)
{
if(i!=2)
{
result.put(fieldsObject.get(i));
}
}
and assign result to original one
fieldsObject=result;
gson library
Remove works for gson library version 2.3.1
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(s).getAsJsonObject();
System.out.println("original object:"+json);
JsonArray fieldsObject = json.getAsJsonArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
org.json library
Remove works for org.json library
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JSONObject json = new JSONObject(s);
System.out.println("original object:"+json);
JSONArray fieldsObject =json.getJSONArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
I tried using org.json library as mentioned by Sanj in the above post. We can remove the element from JSONArray as below. I placed the json content in the .txt file and read into the String object for constructing the JSONObject. Please refer the code below.
public class App{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
String jsonContent = "";
String jsonLine;
while((jsonLine=br.readLine())!=null){
jsonContent+=jsonLine;
}
JSONObject jObj = new JSONObject(jsonContent);
JSONArray jsonArray = jObj.getJSONArray("fields");
jsonArray.remove(1);
System.out.println(jsonArray);
}
}

Categories

Resources