It should look like this:
boolean found = false;
for (int i = 0; i < jsonArray.length(); i++)
if (jsonArray.getString(i).equals(myElementToSearch))
found = true;
I assume that jsonArray has type http://www.json.org/javadoc/org/json/JSONArray.html.
It should look like this:
boolean found = false;
for (int i = 0; i < jsonArray.length(); i++)
if (jsonArray.getString(i).equals(myElementToSearch))
found = true;
I assume that jsonArray has type http://www.json.org/javadoc/org/json/JSONArray.html.
If the object you are comparing against is a primitive type (e.g. int) then try comparing instead of assigning the value.
// Comparing
if (jsonArray[i] == myElementToSearch)
vs
// Assigning
if (jsonArray[i] = myElementToSearch)
If it is an object, such as a String the equals-method should be used for comparing:
// Comparing objects (not primitives)
if (myElementToSearch.equals(jsonArray[i]))
And, if the array is a org.json.JSONArray you use the following for accessing the values:
myElementToSearch.equals(jsonArray.getString(i))
You could try this:
public String returnSearch(JSONArray array, String searchValue){
JSONArray filtedArray = new JSONArray();
for (int i = 0; i < array.length(); i++) {
JSONObject obj= null;
try {
obj = array.getJSONObject(i);
if(obj.getString("name").equals(searchValue))
{
filtedArray.put(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
String result = filtedArray.toString();
return result;
}
Codes are self explanatory, so comments are omitted, hope it helpful.
You can create ArraList of HashMap to store you complete JSON data.
Here is example code.
public String MethodName(String json, String search) {
try {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray(json);
ArrayList<HashMap<String, String>> data = new ArrayList<>();
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (search.equalsIgnoreCase(jsonObject.getString("name"))) {
array.put(jsonObject);
}
}
return array.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Your elements is a JSONArray, but you are trying to parse it as a JSONObject, change your code like this:
JSONObject jsonObject = new JSONObject(PaListContent);
JSONArray myResponse = jsonObject.getJSONArray("elements");
//JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<myResponse.length(); i++){
list.add(myResponse.getJSONObject(i).getString("name"));
}
System.out.println(list);
This will work as expected
But the problem is, that i always get
org.json.simple.JSONObjectcannot be castto org.json.simple.JSONArray. I think the problem is, because my json is an array, but how can i get the attributes?
use JSONArray instead
JSONArray myResponse = jsonObject.getJSONArray("elements");
Here you can find further examples
This is your Json object Format

Try this for getting correct result -
JSONObject list = new JSONObject(content).getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
for (int j = 0; j < resources.length(); j++) {
JSONObject resource = resources.getJSONObject(j).getJSONObject("resource");
JSONObject fields = resource.getJSONObject("fields");
if(fields.getString("symbol").equals("XAG=X")){
System.out.println("Price of symbol(XAG=X) is"+ fields.getString("price"));
}
}
Assuming content represents the json string
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject list = new JSONObject(content).getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
for (int j = 0; j < resources.length(); j++) {
JSONObject resource = resources.getJSONObject(j).getJSONObject("resource");
JSONObject fields = resource.getJSONObject("fields");
System.out.println(fields.get("symbol"));
System.out.println(fields.get("price"));
}
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library? You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You can also use the JsonPath project provided by REST Assured. This JsonPath project uses Groovy GPath expressions. In Maven you can depend on it like this:
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
Examples:
To get a list of all book categories:
List<String> categories = JsonPath.from(json).get("store.book.category");
Get the first book category:
String category = JsonPath.from(json).get("store.book[0].category");
Get the last book category:
String category = JsonPath.from(json).get("store.book[-1].category");
Get all books with price between 5 and 15:
List<Map> books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");
GPath is very powerful and you can make use of higher order functions and all Groovy data structures in your path expressions.
Firstly, add json-path dependency in pom
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Create a utility in Base Class that can be reused :
public static String getValueFromJsonPath(String apiResponse, String jsonPath) {
return JsonPath.read(apiResponse, jsonPath);
}
One example of using this method :
getValueFromJsonPath(apiResponse, "$.store.book[0].category");
NOTE : Create overloaded method with different return types depending upon the expected result (like List for fetching a list from json)
The issue is that you're trying to treat JsonArray to JsonObject. Try the below code and see if it works for you. Point of interest for now is - JsonObject rootObj = rootArr.get(0).getAsJsonObject();
public static void main(String[] args) {
String json = "[{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384640123117E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483379834470379E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384639621985E9,\"uID\":\"136199_3_10\"}]";
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(json);
JsonArray rootArr = root.getAsJsonArray();
JsonObject rootObj = rootArr.get(0).getAsJsonObject();
rootObj.entrySet().forEach(entry -> System.out.println(entry.getKey()+": "+entry.getValue().getAsString()));
}
Here is what you can try
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("JSON Count", jsonArray.get(i).toString());
}
} catch (Exception e) {
}
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:
JSONArray lineItems = jsonObject.getJSONArray("lineItems");
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String key = jsonLineItem.getString("key");
String value = jsonLineItem.getString("value");
...
}
Works great... :)