Get JSON Array into strings. - java

I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks

try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}

Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}

So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.

You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Java jsonObject.get() returns null or an empty object for specific key [duplicate]

This question already has answers here:
Json object returning null against given key
(3 answers)
Closed 5 years ago.
Here's the JSON response.
The following works:
jsonObject.get("title").getAsString();
jsonObject.get("author").getAsJsonObject().get("profile_photo").getAsString();
but jsonObject.get("primary_photo").getAsString() (from line 60) returns an Unsupported Exception: null error. I've tried replacing getAsString() with toString() but the latter returns an empty string.
Try this
Use optJSONObject and optString in your code . And the root is [],so you should use JSONArray
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
// use optJSONObject
JSONObject author = jsonArray.optJSONObject(i).optJSONObject("author");
// use optString , it did not return null
String profile_photo = author.optString("profile_photo");
String primary_photo = jsonArray.optJSONObject(i).optString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Gson
JsonArray jsonElements = new JsonParser().parse(response).getAsJsonArray();
for (int i = 0; i < jsonElements.size(); i++) {
JsonObject jObject = jsonElements.get(i).getAsJsonObject();
// edited here
String primary_photo = jObject.get("primary_photo").getAsString();
JsonObject author = jObject.getAsJsonObject("author");
String profile_photo = author.get("profile_photo").getAsString();
}
I think the Problem is, that your JSON response contains an Array. You have to create an JSONArray from the response-string and than iterate about it to get your values. Or if this array always contains one object:
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Try this,
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject author = jsonArray.get(i).getJSONObject"author");
String profile_photo = author.getString("author");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
try {
JSONArray jarr=new JSONArray(response); // response is whole json response
for (int i=0;i<jarr.length();i++){
JSONObject jobj=jarr.getJSONObject(i);
String primary_photo=jobj.getString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}

How to convert jsonstring to jsonobject in android?

i tried to convert jsonstring to json object. but its convert only first element.
here is my code
String d = [{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}]
JSONObject j = new JSONObject(d);
its give following output
{"name":"kd","isMe":"yes","time":"10:12 AM"}
how can i convert this string into JSNOObject?
You can try like this, and your root is Json array not jsonobject
try {
JSONArray jsonArray = new JSONArray(d);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if(jsonObject == null) {
continue;
}
String name = jsonObject.optString("name");
String isMe = jsonObject.optString("isMe");
String time = jsonObject.optString("time");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Use this
JSONObject jsonObject = new JSONObject(my_json_string);
JSONArray jresult = jsonObject.getJSONArray("array_in_the_json_string");

Trouble extracting values from JSON object in Java

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

json string to java object to populate spinner

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

Parsing JSON Array with JSON OBJECT

I have some JSON with the following structure:
{"cit": [
"ALL",
"Aceh Barat",
"Aceh Besar",
"Aceh Jaya",
"Aceh Selatan",
"Aceh Tengah",
"Aceh Timur",
"Aceh Utara"]}
i have try to parsing my json like this :
JSONObject jsonObject = new JSONObject(result);
JSONArray city=jsonObject.getJSONArray("cit");
for (int j=0; j < city.length(); j++){
JSONObject cit = city.getJSONObject(j);
String kot = cit.toString(j);
kota.add(kot);
}
on post execute :
ArrayAdapter<String> SpinnerKota = new ArrayAdapter<String>(Pencarian.this, android.R.layout.simple_list_item_1, kota);
spin_kota.setAdapter(SpinnerKota);
but nothing happen, is there any wrong with my code? i hope someone can help me to solve my problem.
"cit": [ // json array cit
"ALL", // index 0 is ALL
Also there is no json object inside json array cit. So you don't need this JSONObject cit = city.getJSONObject(j).
Change
String kot = cit.toString(j);
To
String kot = (String) city.get(j);
Use the below
JSONObject jsonObject = new JSONObject("myjson string");
JSONArray city=jsonObject.getJSONArray("cit");
for(int i=0;i<city.length();i++)
{
String cities = (String) city.get(i);
Log.i("All Cities",cities);
kota.add(cities);
}
Do it like this
JSONArray json = jParser.getJSONFromUrl(URL);
JSONObject c = json.getJSONObject(0);
JSONArray city = c.getJSONArray("cit");
for (int j=0; j < city.length(); j++){
String kot = cit.get(j);
kota.add(kot);
}
Object obj = yourJsonResult;
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("cit");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
you can do it as following code this is tested
String jsonSource="{'cit': ['ALL','Aceh Barat','Aceh Besar','Aceh Jaya','Aceh Selatan','Aceh Tengah','Aceh Timur','Aceh Utara']}";
try {
JSONObject jsonObject=new JSONObject(jsonSource);
JSONArray jsonArray=jsonObject.getJSONArray("cit");
int length = jsonArray.length();
String [] cities = new String [length];
if (length > 0) {
for (int i = 0; i < length; i++) {
cities[i] = jsonArray.getString(i);
}
}
//to check we can print our string array
for (int i = 0; i < cities.length; i++) {
Log.d("JSON parsing ",cities[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources