So lets take the following data, I'm using some JSON as below
[
[
"test",
"bob"
],
[
"test2",
"joe"
]
]
Here is my code snippet that I am using:
JSONArray parseContacts = new JSONArray(response);
ArrayList<String> aContacts = new ArrayList<String>();
for (int x = 0; x < parseContacts.length(); x++) {
// i tried aContacts.add(parseContacts.getString(0));
// but of course that wont work
// Now what??
}
I basically want to get the first and second string of each JSON object and of course we use a for loop to get the info, say i want to get the first and second content like this, [x][0] then [x][1], and this would give us "test", "bob", then it would move onto the second object (variable X increments) and give us "test2" and "joe". Any help would be appreciated, thanks!
it's pretty simple:
String test = "[[\"test\",\"bob\"],[\"test2\",\"joe\"]]";
try {
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray array = (JSONArray) jsonArray.get(i);
for (int j = 0; j < array.length(); j++){
// print: array.get(j).toString();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Related
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);
}
}
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 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;
}
I am running a loop where I am getting JSON Objects as inputs how do I append all these JSONObjects in a JSONArray?
The input is a JSONObject which contains a string based key value pair called "name" which I want to extract.
Following is what I tried, I am not able to append all of them together using the following code rather they are appearing one at a time.
List<String> hoi2 = new ArrayList();
if(input != null) {
hoi2.add(input.getString("name"));
}
System.out.println(hoi2);
Sample input format (Getting One Input at a time):
{"lon":77.5858225,"name":"bingo","lat":12.9171587}
{"lon":77.5858225,"name":"dingo","lat":12.9171587}
{"lon":77.5858225,"name":"lingo","lat":12.9171587}
Required result:
["bingo","dingo","lingo"]
My current result:
["bingo"]
["dingo"]
["lingo"]
Update:
I realised the issue my approach was wrong since my array was going blank after every input and re-writing it hence had to define a global variable.
For below code:
List<Integer> hoi2 = new ArrayList<Integer>();
for(int i=0; i<3; i++){
hoi2.add(i);
}
System.out.println(hoi2);
Output will be:
[0, 1, 2]
For below code:
for(int i=0; i<3; i++){
List<Integer> hoi2 = new ArrayList();
hoi2.add(i);
System.out.println(hoi2);
}
Output will be:
[0]
[1]
[2]
JSONArray jArray = new JSONArray();
for (int i = 0; i < docList.size(); i++) {
JSONObject json = new JSONObject(hoi2.get(i));
jArray.put(json);
}
here may post complete solution please refer it.
Code :
List<String> hoi2 = new ArrayList();
hoi2.add("{\"lon\":77.5858225,\"name\":\"bingo\",\"lat\":12.9171587}");
hoi2.add("{\"lon\":77.5858225,\"name\":\"dingo\",\"lat\":12.9171587}");
hoi2.add("{\"lon\":77.5858225,\"name\":\"lingo\",\"lat\":12.9171587}");
JSONArray jsonArray = new JSONArray();
try {
for (int i = 0; i < hoi2.size(); i++) {
JSONObject jsonObject = new JSONObject(hoi2.get(i));
System.out.print(jsonObject.getString("name"));
jsonArray.put(jsonObject.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(jsonArray.toString());
output :
["bingo","dingo","lingo"]
Within this Json response, how do I get access to "smallImageUrls" and get the image url using Java?
Seems like "smallImageUrls" is an array within the "matches" jsonarray. Someone please correct me if I am wrong on that.
{
"attribution":{
"html":"Recipe search powered by <a href='http://www.yummly.com/recipes'><img alt='Yummly' src='http://static.yummly.com/api-logo.png'/></a>",
"url":"http://www.yummly.com/recipes/",
"text":"Recipe search powered by Yummly",
"logo":"http://static.yummly.com/api-logo.png"
},
"totalMatchCount":17663,
"facetCounts":{
},
"matches":[
{
"imageUrlsBySize":{
"90":"http://lh3.ggpht.com/bTkxROvVTjHChEsGLRnkuwPoi-eNrHmESYP3xDHMsIisN-U06z-OfwErSjT5AHvMG0Ccgw8cN4mVqNyjWzbz=s90-c"
},
"sourceDisplayName":"Serious Eats",
"ingredients":[
"mayonnaise",
"crema mexican",
"feta",
"ancho powder",
"garlic",
"coriander leaf",
"shuck corn",
"lime"
],
"id":"Mexican-street-corn-_elotes_-370469",
"smallImageUrls":[
"http://lh5.ggpht.com/itong2VhnBU2mvPtzNimL58MnkC4l113RgNyrEWq8Jf76AsOGOlBoVQyCF-jYDPtzTB-7SoViNzyV5-Xe0NS=s90"
],
"recipeName":"Mexican Street Corn (Elotes)",
"totalTimeInSeconds":2400,
"attributes":{
"cuisine":[
"Mexican"
]
},
"flavors":{
"sweet":0.5,
"sour":0.6666666666666666,
"salty":0.6666666666666666,
"piquant":0.3333333333333333,
"meaty":0.3333333333333333,
"bitter":0.6666666666666666
},
"rating":5
}
],
"criteria":{
"excludedIngredients":null,
"allowedIngredients":null,
"terms":null
}
}
this is the code that I currently have. I can access all the other strings, just not the image urls .
JSONObject resObj = new JSONObject(result);
JSONArray foundrecipes = resObj.getJSONArray("matches");
for(int i = 0;i<foundrecipes.length(); i++){
JSONObject recipe = foundrecipes.getJSONObject(i);
String recipeName = recipe.getString("recipeName");
String rating = recipe.getString("rating");
String id = recipe.getString("id");
String imageurl = recipe.getString("smallImageUrls");
data.add(new Recipes(recipeName, rating, id, imageurl));
}
smallImageUrls, is inside matches that is inside the root, so you have to retrieve matches and, through it, smallImageUrls
JSONObject obj = new JSONObject(...);
JSONArray matches = obj.optJSONArray("matches");
if (matches != null) {
for (int i = 0; i < matchesLenght; i++) {
JSONObject objAtIndex = matches.optJSONObject(i);
if (objAtIndex != null) {
JSONArray smallImageUrls = objAtIndex.optJSONArray("smallImageUrls");
for (int j = 0; j < smallImageUrlsSize; j++) {
String urlAtIndex = smallImageUrls.optString(j);
}
}
}
}