Java JSONObject getJsonArray Blank String - java

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

Related

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

Get string without square brackets

I have json like this
{"First":["Already exists"],"Second":["Already exists"]}
Currently I am doing like
JSONObject jObject = new JSONObject(myJson);
String first = jObject.getString("First")
But I am getting result like this
first = ["Already exists"]
But I want string without square brackets or ""
Try using JSONArray :
JSONArray jArray = new JSONObject(myJson).getJSONArray("First");
String first = jArray.getString(0);
Your json message with key 'first' is Array. So use should treat as Array.
String string = "{'First':['Already exists'],'Second':['Already exists']}";
JSONObject jObject;
try
{
jObject = new JSONObject(string);
Object myJson = jObject.get("First");
if(myJson instanceof JSONArray)
{
JSONArray jArray = jObject.getJSONArray("First");
for (int i = 0; i < jArray.length(); i++)
{
System.out.println("val : "+jArray.getString(i));
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
Thanks to #m.qadhavi i was able to figure out how it works
//This was my temporary solution
//get no. of garage
properties.setPropertyFeaturesGarage(jsonObject
.getJSONObject("extras")
.getString("property_garages")
.replaceAll("[\"]", "")
.replace('[',' ')
.replace(']',' '));
But after going through #m.qadhavi explanation i corrected my code
//get land size
properties.setPropertyFeaturesLandSize(jsonObject
.getJSONObject("extras")
.getJSONArray("property_size")
.getString(0));
Happy Coding
Try to get Substring like e.g.
String first = jObject.getString("First")
String subFirst = first.substring(2,first.length()-2);

AutoSuggest in Android from jsonencoded array of php

I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
try {
String temp=sName.replace(" ", "%20");
URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for(int i = 0; i < jsonResponse.length(); i++){
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
}
}
As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);
Try changing that to:
JSONArray jsonResponse = new JSONArray(line);
You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);

Creating JSONObjects in android

I need to form a JSON object like this.
{
"GroupID": 24536,
"Section": [1,2,3,4,5]
}
Here is what i have tried, but the section array is not getting properly formed when i look at my object structure.
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
Object.put("Section", section);
Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
Integer[] section = {1,2,3,4,5};
Object.put("Section", new JSONArray(Arrays.asList(section)));
Try:
JSONObject Object = new JSONObject();
Object.put("Group", GroupID);
int[] section = {1,2,3,4,5};
JSONArray arr = new JSONArray();
arr.put(section);
Object.put("Section", arr);
Or create a Collection and set it as the value:
Collection c = Arrays.asList(section);
Object.put("Section", c);
You need to make use of JSONArray for inserting set of values that represent an array, in this case int array.
String strJson = null;
try{
int[] section = {1,2,3,4,5};
JSONObject jo = new JSONObject();
jo.put("GroupId", 24536);
JSONArray ja = new JSONArray();
for(int i : section)
ja.put(i);
jo.put("Section", ja);
strJson = jo.toString();
}
catch (Exception e) {
e.printStackTrace();
}
Now you've got json string inside strJson.

Categories

Resources