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();
}
Related
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");
I have an ArrayList containing a list of JSONArrays
staffArray = new ArrayList<JSONArray>();
the JSONArray is in a form of this:
[
{
"id": "k40dn-dff02-mm1",
"name": "staff1",
"tel": "0123456789",
},
{
"id": "ch2mq-pmw01-ps6",
"name": "staff2",
"tel": "9876543210",
}
...
]
And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.
So far I have tried this to extract the string:
for(int i = 0; i < staffArray.size(); i++){
JSONArray jsonArray = new JSONArray();
jsonArray = staffArray.get(i);
for(int j = 0; j < jsonArray.length(); j ++){
JSONObject json = null;
try {
json = jsonArray.getJSONObject(j);
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
If you would like to check for duplicate IDs in your ArrayList, you could do something like this:
ArrayList<JSONArray> staffArray = new ArrayList<>();
Set<String> ids = new HashSet<>();
for (JSONArray array : staffArray) {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (!ids.add(obj.getString("id"))) {
// duplicate IDs found, do something
}
}
}
How about using group by to group the json arrays with same id something like this
public static void groupById(List<JSONArray> staffArray) {
Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
jsonArraysById.forEach((id, arrays) -> {
System.out.println("Arrays with id " + id + " are " + arrays);
});
}
public static String getIdFromJsonArray(JSONArray jsonArray) {
String result = null;
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(j);
result = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
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;
}
}
from the following link , I need to get the value stored in "media".
Here is my code:
Content = Content.replace("jsonFlickrFeed(", "");
Content = Content.replace("})", "}");
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
But I can not access past "items"
You will have to loop through the JSON like this:
...
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
String media = jsonMainNode.getJSONObject(i).getString("media");
}
This will loop through the images and return the value(s) in media.
In your case it should be something like this:
..
JSONArray jsonMainNode = jsonResponse.optJSONArray("items");
for (int i=0; i<jsonMainNode.length(); i++) {
JSONObject finalNode = jsonMainNode.getJSONObject(i);
JSONArray finalArray = finalNode.optJSONArray("media");
for (int j=0; j<finalArray.length(); j++) {
String m = finalArray.getJSONObject(j).getString("m");
}
}
...because there is another node inside the media node, called m.
Here is an example getting the tags string for each item in the JSONArray that you have:
for (int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonObject = jsonMainNode.getJSONObject(i);
String tags = jsonObject.getString("tags");
}
This will iterate through all JSONObjects that are in the array, and extract the tags field from each object.
JSONArray jsonMainNode = jsonResponse.optJSONArray("items"); // this works great!
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject item = (JSONObject) jsonMainNode.get(i);
JSONObject media = item.getJSONObject("media");
String valueMedia = media.getString("m");
Log.d("TAG", valueMedia);
}
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();
}
}