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.
Related
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
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());
}
}
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
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"));
}
}
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) {
}