How to search in a JSON file - java

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

Related

How to parse array into array JSON

first of all I wanted to know if the structure of the json is correct, you can find the JSON here:
http://demo8461125.mockable.io/whitemage
if it is correct I would like to know how to parse "PANINI" , is an array inside an array "tipopietanza"
JSONArray arr = response.getJSONArray("pietanze");
for (int i = 0; i < arr.length(); i++)
{
JSONArray pietanze = response.getJSONArray("PANINI");
List<Pietanze> listapietanze =new ArrayList<>(pietanze.length());
for(int j=0;j<pietanze.length();j++)
{
Pietanze tmp = new Pietanze();
tmp.setNome(pietanze.getJSONObject(j).getString("nomepietanza"));
listapietanze.add(tmp);
}
expandableListDetail.put(arr.getJSONObject(i).getString("tipopietanza"), listapietanze);
}
Yes, it should work, but I suggest just use Gson:
Type type = new TypeToken<List<TipiPaniniAndServizi>>(){}.getType();
List<TipiPaniniAndServizi> tipiPaniniAndServizi = gson.fromJson(json, type);
And save your time from manipulate JSON, just think about your java objects.
JSON structure is okay.
You need to do minor changes in your code for getting list properly.
JSONArray arr = response.getJSONArray("pietanze");
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
if(jsonObject.has("PANINI")) {
JSONArray paniniJsonArray = jsonObject.getJSONArray("PANINI");
List<Panini> listPanini = new ArrayList<>();
for (int j = 0; j < paniniJsonArray.length(); j++) {
Panini panini = new Panini();
panini.setId(paniniJsonArray.getJSONObject(j).getString("id"));
panini.setNomepietanza(paniniJsonArray.getJSONObject(j).getString("nomepietanza"));
panini.setPrezzo(paniniJsonArray.getJSONObject(j).getString("prezzo"));
listPanini.add(panini);
}
expandableListDetail.put(arr.getJSONObject(i).getString("tipopietanza"), listPanini);
}
}

Fetch value from JSON array based on another value in the array

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

Compare list of JSONArray in ArrayList

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

new to json parsing - how to get an array within an array

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

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