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;
}
Related
I am having a JSON file that consists of JSON Objects and arrays. The file looks like this:
{"Report": {"Information": [
{
"table_name1": [
{"ID": 312},
{"LASTNAME": "TESTER2"},
{"GUID": "ADSA31321"},
{"PHONE_MOBILE": 931024}}
],
"table_name2": [
{"ID": 312},
{"PID": "TESTER2"},
{"GUID": "ADSA31321"}
]
}
]}}
I am trying to update the values within the table_name array. The problem is that this name is dynamic and not a static name given to the array.
I am using the Java class below to reach ID.
if( inputJs.getJSONObject("Report").get("Information") instanceof JSONArray) {
JSONArray val= inputJs.getJSONObject("Report").getJSONArray("Information");
for(int i = 0; i < val.length(); i++) {
JSONArray jsa2=val.getJSONArray(i);
for(int j = 0; j < jsa2.length(); j++) {
JSONObject jso= jsa2.getJSONObject(j);
if(jso.equals("GUID")) {
jso.put("GUID", GetRegExpr(3));
}
}
}
}
This line : JSONArray jsa2=val.getJSONArray(i); creates the error below:
org.json.JSONException: JSONArray[0] is not a JSONArray.
even though "table_name1" is a JSONArray.
Any help will be appreciated.
Try this...
informationList = new JSONObject().getJSONObject("Report").getJSONArray("Information");
for (int i = 0; i < informationList.length(); i++) {
JSONObject information = informationList.getJSONObject(i);
Iterator<String> keys = information.keys();
while (keys.hasNext()) {
String tableName = keys.next();
JSONArray table = information.getJSONArray(tableName);
for (int j = 0; j < table.length(); j++) {
JSONObject data = table.getJSONObject(j);
String k = data.keys().next();
if (k.equals("GUID")) {
data.put("GUID", "edit ...");
}
}
}
}
If I were you, I would use other library like Gson...
Please replace your code with the one below
if( inputJs.getJSONObject("Report").get("Information") instanceof JSONArray){
JSONArray infoArray = inputJs.getJSONObject("Report").get("Information");
for (int i = 0; i < infoArray.length(); i++) {
JSONObject information = infoArray.getJSONObject(i);
Iterator<String> keys = information.keys();
while (keys.hasNext()) {
String tableName = keys.next();
JSONArray table = information.getJSONArray(tableName);
for (int j = 0; j < table.length(); j++) {
JSONObject data = table.getJSONObject(j);
String k = data.keys().next();
if (k.equals("GUID")) {
data.put("GUID", GetRegExpr(3));
}
}
}
}
}
you can try like this :
if( inputJs.getJSONObject("Report").get("Information") instanceof JSONArray){
JSONArray val= inputJs.getJSONObject("Report").getJSONArray("Information");
for(int i=0;i<val.length();i++){
JSONObject jsa2=val.getJSONObject("table_name"+i); // table_name1,table_name2,...
for(int j=0;j<jsa2.length();j++){
JSONObject jso= jsa2.getJSONObject(j);
if(jso.equals("GUID")){
jso.put("GUID",GetRegExpr(3));
}
}
}
Here is my JSON response:
[
{
"name":"Canara Atm",
"location_name":"Baker Junction"
},
{
"name":"Canara Atm",
"location_name":"Manarcaud"
},
{
"name":"Canara Atm",
"location_name":"Palai Arunapuram"
},
{
"name":"Canara Atm",
"location_name":"Changanacherry"
}
]
I need to get add values based on a specific location in to to the array, means, for example, location_name":"Baker Junction" is my needed location then to my array I should add only the specified atm name. in the below code all names are being added to the array
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject json = null;
final String xcoords[] = new String[jsonArray.length()];
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
json = jsonArray.getJSONObject(i);
xcoords[i] = (json.getString("name"));
}
}
}
this is what i did , you can convert json to list like given below ,
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
json = jsonArray.getJSONObject(i);
Strring s = (json.getString("name"));
list.add(p)
}
then
//you can directly use this value or you can use the index to again fetch the json or for other purpose
int count =0;
int index = 0 ;
for(Sting s : list){
if(s.equals("yourvalue"){
index = count;
}
count++
}
then
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
// your index here
json = jsonArray.getJSONObject(index);
xcoords[i] = (json.getString("name"));
}
}
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();
}
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();
}
}
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();
}