Build JSON Array from JSON Objects - java

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"]

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

How to parse array with multiple indexes only in Java Android

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

android reverse int array

I have successfully parsed JSONArray into list by using the below function
public List<Integer> ParseJson(String json, List<Integer> myList) {
JSONArray jsonArray = null;
try {
JSONObject mainJson = new JSONObject(json);
jsonArray = mainJson.getJSONArray("result");
myList = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
myList.add(Integer.parseInt(jsonArray.get(i).toString()));
}
// System.out.println(myList);
} catch (JSONException e) {
e.printStackTrace();
}
Collections.reverse(myList);
return myList;
}
Now I need the List into reverse order. What would be the optimized way to do that?
Before you edited your question it seemed like you wanted to reverse the JSON array, append it to "myList" and return the result. If that's true, try this:
public List<Integer> ParseJson(String json, List<Integer> myList) {
JSONArray jsonArray = null;
try {
JSONObject mainJson = new JSONObject(json);
jsonArray = mainJson.getJSONArray("result");
List<Integer> reverseListFromJson = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
reverseListFromJson.add(jsonArray.getInt(i));
}
Collections.reverse(reverseListFromJson);
myList.addAll(reverseListFromJson);
} catch (JSONException e) {
e.printStackTrace();
}
return myList;
}
[1,2,3,5,23,534,23]: Your JSONArray already contains ints, no need to convert.
JSONArray jsonarray = getTheJSONArrayFromSomewhere();
Log.d(TAG, jsonarray.toString(4)); // for debugging purposes. Check the contents of the jsonarray
List<Integer> list = new ArrayList<Integer>();
for (int i = jsonarray.length() - 1; i >= 0; i--)
list.add(jsonarray.getInt(i));
or this
JSONArray jsonarray = getTheJSONArrayFromSomewhere();
Log.d(TAG, jsonarray.toString(4)); // for debugging purposes. Check the contents of the jsonarray
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < jsonarray.length(); i++)
list.add(jsonarray.getInt(i));
Collections.reverse(list);
That does reverse your Integer List, assuming your JSONArray is filled correctly, and contains ints. Also, I omitted try/catch, you'll have to add those.
use below code to do this
ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);
hope it will work for you
Have you tried using:
ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);

Java how to remove strings from JSONArray

JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
lets say we have this jsonArray, there are strings empty, how to remove them without leaving gaps?
You can use the following code :
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String val = jsonArray.getJSONObject(i).getString();
if (val.equals("empty")) {
jsonArray.remove(i);
}
}
take a look at this post.
Make a list to put the indexes of the elements with the "empty" string and iterate over your list (the one with the "empty" elements) saving the indexes of the items to delete. After that, iterate over the previosly saved indexes and use
list.remove(position);
where position takes the value of every item to delente (within the list of index).
Should work with few fixes to Keerthi's code:
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.get(i).equals("empty")) {
jsonArray.remove(i);
}
}
You can use this following code
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item string equal to "empty"
if (!"empty".equals(jsonArray.getString(i))
{
list.put(jsonArray.get(i));
}
}
//Now, list JSONArray has no empty string values
}
you can use string replace after converting the array to string as,
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");
System.err.println(jsonArray);
String jsonString = jsonArray.toString();
String replacedString = jsonString.replaceAll("\"empty\",", "").replaceAll("\"empty\"", "");
jsonArray = new JSONArray(replacedString);
System.out.println(jsonArray);
Before replace:
jsonArray is [1,"empty",2,3,"empty",4,"empty"]
After replace:
jsonArray is [1,2,3,4]

Initializing array for JSON data advice

I am trying to store data gotton from JSON to an normal string array. The problem is i cant seem to initialize the array size according to the number for JSON data.
For now i declare the array size my own:
String[] path= new String[5];
This is the JSON part:
class Loadpath extends AsyncTask {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_imageDB, "GET",params);
try {
JSONArray productObj = json.getJSONArray(TAG_IMAGEDB); // JSON Array
// looping through All path
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
path[i] = image.getString(TAG_PATH);
}
} else {
displayPath.setText("No path");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
So my goal is the array size is gotten from the JSON.length().. Any idea how I can achieve this?
initialize the mStrings[ ] array size according to the JSONArray length as:
String[] mStrings; //<< Declare array as
mStrings = new String[productObj.length()]; //<<initialize here
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings[i] = image.getString(TAG_PATH);
}
and it is good if you use ArrayList instead of String Array as for getting values from Jsonobject as:
ArrayList<String> mStrings=new ArrayList<String>(;
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings.add(image.getString(TAG_PATH));
}
Maybe u can use List instead of String array

Categories

Resources