JSONArray arr =
[
{"key1":"value1"},
{"key2":"value2"},
{"key3":"value3"},
{"key4":"value4"}
]
arr.get("key1") throws error. How can I get the value by key in JSONArray?
arr.getString("key1") also throws error. Should I loop through the array? Is it the only way to do it?
What is the error?
In Eclipse Debug perspective, these expressions returns as; error(s)_during_the_evaluation
You can parse your jsonResponse like below code :
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String value1 = jsonObject1.optString("key1");
String value2 = jsonObject1.optString("key2");
String value3 = jsonObject1.optString("key3");
String value4 = jsonObject1.optString("key4");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Sounds like you want to find a specific key from an array of JSONObjects. Problem is, it's an array, so you have to iterate over each element. One solution, assuming no repeat keys is...
private Object getKey(JSONArray array, String key)
{
Object value = null;
for (int i = 0; i < array.length(); i++)
{
JSONObject item = array.getJSONObject(i);
if (item.keySet().contains(key))
{
value = item.get(key);
break;
}
}
return value;
}
Now, let's say you want to find the value of "key1" in the array. You can get the value using the line: String value = (String) getKey(array, "key1"). We cast to a string because we know "key1" refers to a string object.
for (int i = 0; i < arr.length(); ++i) {
JSONObject jsn = arr.getJSONObject(i);
String keyVal = jsn.getString("key1");
}
You need to iterate through the array to get each JSONObject. Once you have the object of json you can get values by using keys
You can easy get a JSON array element by key like this:
var value = ArrName['key_1']; //<- ArrName is the name of your array
console.log(value);
Alternatively you can do this too:
var value = ArrName.key_1;
That's it!
Related
I have a list of objects and am converting into JSONArray. Am iterating over the JSONObjects and making an array of JSONObjects.
Now, i want to avoid duplicates objects to get insert into the JSONArray.
Please find my java code below.
JSONArray responseArray1 = new JSONArray();
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String attr_label = jsonObj.optString("attr_label");
if(StringUtils.equalsIgnoreCase(attr_label, "long_description")) {
long_description = jsonObj.optString("value");
}
else if(StringUtils.equalsIgnoreCase(attr_label, "description")) {
description = jsonObj.optString("value");
}
responseObj.put("id", jsonObj.opt("id")); // i will get duplicate id
responseObj.put("code", jsonObj.opt("code")); // i will get duplicate code
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray1.put(responseObj);
}
}
Please find my actual jsonArray :
[
{
"code":"xyaz",
"attr_label":"long_description",
"id":"12717",
"value":"Command Module"
},
{
"code":"xyaz",
"attr_label":"description",
"id":"12717",
"value":"Set Point Adjustment"
},
]
Am expecting like the below jsonArray :
[
{
"code":"xyaz",
"id":"12717",
"long_description":"Command Module"
"description" : "Set Point Adjustment"
}
]
Update :
I have tried with the below code to avoid duplicate insertion of id & code field. but is not working properly. Its inserting duplicates also.
List<String> dummyList=new ArrayList<String>();
JSONArray responseArray2 = new JSONArray(itemList);
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String itemCode = jsonObj.optString("code");
String id = jsonObj.optString("id");
if(!dummyList.contains(itemCode) && !dummyList.contains(id) ) {
dummyList.add(String.valueOf(jsonObj.opt("id")));
dummyList.add(String.valueOf(jsonObj.opt("code")));
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray2.put(responseObj);
}
}
}
Make a temporary array list and add unique code in that arrayList and check if it already exists in arrayList then don't put this again
String code = jsonObj.opt("code");
if(!arrayList.contains(code))
{
arrayList.add(code);
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
}
use TreeSet and add Comparator to their constructor in which it compare the duplicate data of the object.
for example:-
Set<Sample> sampleSet=new TreeSet<>(new Sample());
where Sample Class look like:-
class Sample implements Camparator<Sample>{
private String name;
private String id;
//getter
//setter
#Override
public String compare(Sample o1,Sample o2){
return o1.getName.compareTo(o2.getName);
}
}
This will give a set of unique name entries.
I have following JSONObject (not array, which I don't mind to convert). I am trying to do two things:
get the count of genre entry as "poetry" (count = 2).
get the key value of author name and genre:
authorName = malcolm
genreName = newsarticle
authorName = keats
genreName = poetry
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
Code which I tried:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
I have looked at solutions all over. There is no question similar to this at stackoverflow. I am not sure if the procedure is correct.
A few problems here.
First, I'm not sure where you got that example JSON but you can't work with that. That's not even valid JSON Formatting.
Looks like you want something like this:
{
AddressBook:
[
{
authorname: "author-malcom",
genre:"poetry"
},
{
authorname: "author-keats",
genre: "poetry"
}
]
}
That's the structure you're trying to create in JSON.
So, you're parsing this in from a file into a JSONObject that has a key called AddressBook inside of it. That key points to an array of JSONObjects representing authors. Each of those objects will have a key called genre. You're trying to access the genre key and count on a condition.
What you did above was create attempt to create a JSONObject from an invalid string, and then add the entire JSONObject itself into the JSONArray. JSONArray.add() doesn't convert an object to an array, it literally adds it onto the array.
jsonObj => {"Name":"name1","Id":1000}
jsonArray.add(jsonObj)
jsonArray => [{"Name":"name1","Id":1000}]
That's what you did in your code above. You didn't create an array from a JSONObject, you added an object to the array.
Proper use is going to look like:
Object obj = parser.parse(new FileReader("path_to_file"));
JSONObject jobj = (JSONObject) obj;
//access key AddressBook
JSONArray author_array = jobj.getJSONArray("AddressBook");
int poetry = 0;
for(int i = 0; i < author_array.length(); i++) {
JSONObject author = (JSONObject) author_array.get(i);
if(author.getString("genre").equals("poetry")) {
poetry++;
}
}
To summarize, you're problems come from a lack of understanding about JSON Formatting and how to access elements within a JSON Object.
Paste in the sample JSONObject I gave you above here. That site will let you visualize what you're working with.
I have been trying to get the key and value of my JSONObject. I have no idea why this isn't working, because String key is clearly a string?
My code:
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = obj.getString(key); //This is where the error comes
}
The JSONObject:
{
"relatie_website": ["www.apple.com"],
"relatie_kvknummer": ["NL3234234"],
"relatie_naam": ["Apple international inc."],
"relatie_d400code": [null],
"relatie_zoeknaam": ["APPLE INC"],
"relatie_debiteurnummer": ["3523523"],
"relatie_btwnummer": ["332342"]
}
This is the error I have been getting:
org.json.JSONException: JSONObject["relatie_website"] not a string.
You should change your object to be sth like that :
{
"relatie_website": "www.apple.com",
"relatie_kvknummer": "NL3234234",
"relatie_naam": "Apple international inc.",
"relatie_d400code": null,
"relatie_zoeknaam": "APPLE INC",
"relatie_debiteurnummer": "3523523",
"relatie_btwnummer": "332342"
}
Because the problem is that your values are an array and not a string.
But if you need te keep your values in an array you can change your code to support the arrays :
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
JSONArray value = obj.getJSONArray(key);
}
And you will have a JsonArray that you can manipulate as you want by doing sth like that :
for (int i = 0; i < value.length(); i++) {
String val = value.getString(i).toString();
logger.info("val : " + val);
}
after sorting by ascending order the below is the json array i am getting
[{"id":0,"dependency":"no","position":0,"Itype":"textinput","label":"t01"},{"id":0,"dependency":"no","position":1,"label":"t02","type":"textarea"},{"id":1,"dependency":"no","position":2,"type":"textinput","label":"t03"},{"id":1,"dependency":"no","position":3,"type":"textarea","label":"t04"}]
I am building up text field or textaaarea according to type or itype in json array but am getting exception "NO value for id"
This is the code so far
//Sorting function called
org.json.JSONArray finalSortedarray=Sort.Sort(formdataArray);
System.out.println("After Function Called Array------------>"+finalSortedarray);
/*for(int v=0;v<finalSortedarray.length();v++){
String sv=(String) formdataArray.getJSONObject(v).get("type");
System.out.println(sv);
}*/
for(int v=0;v<finalSortedarray.length();v++){
JSONObject obj1=(JSONObject)finalSortedarray.getJSONObject(v);
Iterator<String> Nkeys= obj1.keys();
while(Nkeys.hasNext()){
String Nkey=Nkeys.next();
JSONArray Nval=obj.getJSONArray(Nkey);
System.out.println("NVAL IS----->"+Nval);
//formdataArray.getJSONObject(v).get("type");
}
}
Please Help
for(int v=0;v<finalSortedarray.length();v++){
JSONObject obj1=(JSONObject)finalSortedarray.getJSONObject(v);
String id = obj1.getString("id");
String dependency= obj1.getString("dependency");
String position= obj1.getString("position");
//...
}
use like this
try{
JSONArray array = new JSONArray(response)
for(int i = 0; i<array.length();i++)
{
JSONObject obj1 = array.getJSONObject(i);
String id = obj1.getString("id");
String dependency= obj1.getString("dependency");
String position= obj1.getString("position");
String Itype= obj1.getString("Itype");
String label= obj1.getString("label");
}
}
catch(Exception e){
Log.d("","Error : "+e.toString());
}
happy to help
How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling