im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.
public static String constructJSON(Integer[] array, String[] array2) {
JSONObject mainObj = new JSONObject();
try {
JSONObject firstArray = new JSONObject();
firstArray.put("array0", array[0]);
firstArray.put("array1", array[1]);
firstArray.put("array2", array[2]);
firstArray.put("array3", array[3]);
firstArray.put("array4", array[4]);
JSONObject secondArray = new JSONObject();
secondArray.put("sArray0", array2[0]);
secondArray.put("sArray1", array2[1]);
secondArray.put("sArray2", array2[2]);
secondArray.put("sArray3", array2[3]);
secondArray.put("sArray4", array2[4]);
JSONArray JArr = new JSONArray();
JArr.put(firstArray);
JArr.put(secondArray);
mainObj.put("arrays", JArr);
} catch (JSONException e) {
}
return mainObj.toString();
}
And now the method in Android Studio:
private void getBW(String krankheit) {
RequestParams params = new RequestParams();
params.put("krankheit", krankheit);
// Invoke RESTful Web Service with Http parameters
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
// JSON Object
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("array1");
JSONArray secondJsonArr= obj.getJSONArray("array2");
for (int k = 0; k < 5; k++) {
Bewertung1[k] = (Integer) firstJsonArr.get(k);
}
for (int j = 0; j < 5; j++) {
medikament[j] = (String) secondJsonArr.get(j);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
I tried different solution´s, but none of them worked for me. I hope you guys can help me.
I would recommend you to use gson library for android. Its provides simple function to parse from and to json object.
Have a look at this library : https://github.com/google/gson
You switched your function istead of what you wanted it does [{}{}]
Try this:
public static String constructJSON(Integer[] array, String[] array2) {
try {
JSONArray firstArray = new JSONArray ();
firstArray.put( array[0]);
firstArray.put( array[1]);
firstArray.put( array[2]);
firstArray.put( array[3]);
firstArray.put( array[4]);
JSONArray secondArray = new JSONArray ();
secondArray.put(array2[0]);
secondArray.put( array2[1]);
secondArray.put( array2[2]);
secondArray.put( array2[3]);
secondArray.put( array2[4]);
JSONObject JArr = new JSONObject();
JArr.put("firstArr",firstArray);
JArr.put("secondArr", secondArray);
return JArr.toString();
} catch (JSONException e) {
}
return null;
}
this will give you the JSon you wanted , and this is the main code to use it:
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}
this is good for practices but later you should use a library that does these type of things for you like Gson etc...
Related
I'm trying to use JSONObject's put method in for loop. But I'm not getting Expected output.
Expected output:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"},{"PostOfficeName":"Gokulpuri","Pincode":"110094"}, and so on...]}
OutPut I'm getting:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"}]}
here is my code:
try {
JSONObject obj = new JSONObject(loadJsonfromAssets());
JSONArray arr = obj.getJSONArray("Sheet1");
JSONObject finalObj = new JSONObject();
JSONArray ResultArray = new JSONArray();
JSONObject infoObj = new JSONObject();
for (int i=0; i<arr.length();i++){
JSONObject obj1 = arr.getJSONObject(i);
if (obj1.getString("City").equals("New Delhi")){
Log.d("postal", "Found!");
Toast.makeText(this, "" + obj1.getString("Pincode"), Toast.LENGTH_SHORT).show();
infoObj.put("PostOfficeName", obj1.getString("PostOfficeName"));
infoObj.put("Pincode",obj1.getString("Pincode"));
ResultArray.put(infoObj);
}
}
finalObj.put("Result", ResultArray);
System.out.println(finalObj);
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried moving the construction of infoObj inside the loop. By having it outside, you're maintaining state across loop iterations. I suspect you're just updating the same json object each time and adding it to the JSON array. Not sure why you NOT getting duplicates because I do when I run your code.
Change it to this makes it "better"
try {
JSONObject obj = new JSONObject(loadJsonfromAssets());
JSONArray arr = obj.getJSONArray("Sheet1");
JSONObject finalObj = new JSONObject();
JSONArray ResultArray = new JSONArray();
for (int i=0; i<arr.length();i++){
JSONObject obj1 = arr.getJSONObject(i);
if (obj1.getString("City").equals("New Delhi")) {
Log.d("postal", "Found!");
Toast.makeText(this, "" + obj1.getString("Pincode"),
Toast.LENGTH_SHORT).show();
// move instantiation INSIDE loop
JSONObject infoObj = new JSONObject();
infoObj.put("PostOfficeName", obj1.getString("PostOfficeName"));
infoObj.put("Pincode",obj1.getString("Pincode"));
ResultArray.put(infoObj);
}
}
finalObj.put("Result", ResultArray);
System.out.println(finalObj);
} catch (JSONException e) {
e.printStackTrace();
}
Okay, I'm struggling here. I am getting the following JSON formated string from my php server (called "result") (edited! I was missing a curly brace at the end):
{"L1":[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}],"L2":[{"UserName":"User4","Avatar":"4"},{"UserName":"User5","Avatar":"5"}]}
I'm trying to extract an ArrayList with the Avatar numbers from the L1 object(?). But I get an error
org.json.JSONException: Value
[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}]
at L1 of type org.json.JSONArray cannot be converted to JSONObject
Here's my code:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
} catch (JSONException e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
If I use
jsonObject.getJSONArray("L1")
I get the same error.
Any suggestions?
Thanks in advance!
(edit: I made a mistake in the original post. There was a missing curly brace in the JSON string. Thanks to those who caught that)
Try the below one.Its working fine. I'm using json-simple-1.1.1 jar
String r="{\"L1\":[{\"UserName\":\"User1\",\"Avatar\":\"1\"},{\"UserName\":\"User2\",\"Avatar\":\"2\"},{\"UserName\":\"User3\",\"Avatar\":\"3\"}],\"L2\":[{\"UserName\":\"User4\",\"Avatar\":\"4\"},{\"UserName\":\"User5\",\"Avatar\":\"5\"}]}";
Object obj=JSONValue.parse(r);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("L1");
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject json = (JSONObject) jsonArray.get(i);
arrList.add((Integer.parseInt((String) json.get("Avatar"))));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
This ended up working for me if anyone stumbles upon this. I don't really understand why this worked and my original method didn't... something to do with JSONObjects vs JSONArrays vs Strings and things like [, {, }, and ] probably.
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getString("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
I hava this JSON:
[
{
"title": "This a Sample title for each post_title",
"excerpt": "And this is a sample of the post_body,
"author": "King Spark",
"featured_picture": {
"source": "https://exapmple.com/blah/blah/image.jpg",
"year": "2015",
"ownwer": "Akim Man",
},
},...
From the json I only need the title, excerpt elements of the main objects. Then from the featured_picture objects, I want only the source element.
I have written this code and it seems not to be working:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
Try to parse the nested JSON like this way:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_picture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
postItem.setPost_image(postImage.getString("source"));
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
You won't continue read the array here
for (int f = 0; f<array.length(); f++) {
featured_picture is an entry in the map and returns a map too.
The acces should be like this :
array.getJSONObject(i).getJSONObject("featured_picture").getString("source");
You have to identify object and array in json then find value by key, once you learnt then complexity of json doesn't matter to parse follow tutorial
your code for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
is not correct, this part of json is not an array but an object inside another jsonObject.
Here no need to iterate loop to read nested JSONobject.
Because "featured_picture" gives only JSONObject not an array. In case if its return array you should read like this:
JSONObject rootObject=new JSONObject();
JSONArray nestedObject=rootObject.getJSONArray("key");
Here i modified your code in correct manner hope will it help for you.
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
So i have a Json string that i have retrieved from my PHP script on my MySQL server
{"Clientid":[24,26,27],"companyname":["chelsea","Microsoft","IBM"]}
and i have been trying to push this into a java objects in-order to populate a spinner at the moment the spinner on each line shows "chelsea","Microsoft","IBM" but i would like to show each company on a separate line so the user can select which company
current code
String response = stringBuilder.toString();
Log.d("response", response);
JSONObject jsonResponse = new JSONObject(response);
Log.d("response", jsonResponse.toString());
responseStreamReader.close();
Log.d("length", Integer.toString(jsonResponse.length()));
if (jsonResponse.length() == 0) {
returnedClient = null;
} else {
List<Client> myClients;
myClients = new ArrayList<Client>();
for (int i = 0; i < jsonResponse.length(); i++) {
Client client = new Client();
client.clientid = jsonResponse.getString("Clientid");
client.companyname = jsonResponse.getString("companyname");
myClients.add(client);
}
returnedClient = myClients;
}
} catch (Exception e) {
e.printStackTrace();
}
//Log.d("returnedUser", returnedUser.userpassword);
return returnedClient;
current code is obviously the wrong code so i have been looking at Gson and Jackson and volley and getting in a mess so i have been looking at the below but cant get it right to fit the Json string so wondered if you could help please or advise a better solution?
JSONArray jarray = jsonResponse.getJSONArray("companyname");
ArrayList<String> xyz= new ArrayList<String>();
for(int i = 0; i < jarray.length(); i++){
JSONArray timeArray =jarray.getJSONObject(i).getJSONArray("companyname");
for(int j = 0; j < timeArray .length(); j++){
xyz.add(timeArray .getString(j));
Log.d("get value",timeArray .getString(j));
Is there something im missing with the parser as doesnt matter what i change it seems to not like anything i do, it says the json cant be an object then it cant be an array, i assume the json is an object then an array but at the mormnt i just get errors :(
try {
List<Client> returnedClient = null;
// JSONObject json = new JSONObject(content);
JSONArray json1 = new JSONArray(content);
//JSONObject dataObject1 = json.getJSONObject("Clientid");
//JSONObject dataObject2 = json.getJSONObject("companyname");
// JSONArray items1 = json.getJSONArray("Clientid");
// JSONObject items2 = json.getJSONObject("companyname");
// JSONArray items1 = json.getJSONArray("Clientid");
JSONArray items2 = json1.getJSONArray(0);
for (int i = 0; i < items2.length(); i++) {
// JSONArray clientObject1 = items1.getJSONArray(i);
// JSONObject clientObject2 = items2.getJSONObject(i);
JSONArray clientObject3 = items2.getJSONArray(i);
// Client client = new Client(clientObject2);
Log.d("response",clientObject3.toString());
// returnedClient.add(client);
}
O silly me the is was further up the tree as i was using the code below at the top of the page before i even started the parse, shame it took me to re write my sql before i noticed :(
JSONObject jsonResponse = new JSONObject(response);
I submit a query from my Java application, which upon running on Elasticsearch server returns the result in the form of a string. I want the result as a list of JSONObject objects. I can convert the string to a JSONObject using JSONObject jsonResponse = new JSONObject(responseString).
Is there any method by which I can get this in the form of a List<JSONObject>?
Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
There is an answer of your question:
https://stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
This method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}