get a Json value without string key - Java JSONObject - java

It' easy to get a value from JSON when you have the string key, but what if you have situation like that:
{
"images":["URL1"]
}
And array and no key inside? I use this code:
JSONArray imagesArr = propertiesjsonObject.getJSONArray("images");
for (int y=0; i<imagesArr.length(); y++)
{
JSONObject imagesJsonObject = imagesArr.getJSONObject(y);
String str_image_url = imagesJsonObject.get("HOW TO GET THE VALUES HERE?");
}
Propably it's ultra easy. Sorry to ask but I could not find proper example. PS. I use: import org.json.JSONArray;
import org.json.JSONObject;
PS2: For now there is only one element in array, but in future I suppouse there might be more.

Try with this:
ArrayList<String> urls = new ArrayList<String>();
JSONArray imagesArr = propertiesjsonObject.getJSONArray("images");
for (int i = 0; i < imagesArr.length(); i++) {
String str_image_url = imagesArr.getString(i);
urls.add(str_image_url);
}
urls is an array with all the url you got
Hope this helps

String str_image_url = imagesArr.getString(0);//you specify position in array here

Related

How to get a value which is a List from a JSONObject in Java

I have a following JSON:
{"data":["str1", "str2", "str3"]}
I want to get a List, i.e. ["str1", "str2", "str3"]
My code is:
JSONObject json = new JSONObject();
List list = new ArrayList();
...
// adding data in json
...
list = (List) json.get("data");
This is not working.
you can get this data as a JsonArray
You can customize a little bit of code like it
public static void main(String[] args) throws ParseException {
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(
data);
JSONArray jasonArray = json.getJSONArray("data");
List list = new ArrayList();
int size = jasonArray.length();
int i = 0;
while (i < size) {
list.add(jasonArray.get(i));
i++;
}
System.out.println(list);
}
You wish to parse a JSON string using Java code. It is recommended to use a JSON library for Java. There are several. The below code uses Gson. There are many online examples such as Convert String to JsonObject with Gson. You should also familiarize yourself with the Gson API.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class JsonList {
public static void main(String[] args) {
String json = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JsonElement elem = JsonParser.parseString(json);
if (elem.isJsonObject()) {
JsonObject obj = elem.getAsJsonObject();
elem = obj.get("data");
if (elem.isJsonArray()) {
JsonArray arr = elem.getAsJsonArray();
List<String> list = new ArrayList<>();
int count = arr.size();
for (int i = 0; i < count; i++) {
elem = arr.get(i);
if (elem.isJsonPrimitive()) {
String str = elem.getAsString();
list.add(str);
}
}
System.out.println(list);
}
}
}
}
Running the above code gives the following output:
[str1, str2, str3]
There are other ways to convert the JsonArray to a List. The above is not the only way. As I wrote earlier, peruse the API documentation and search the Internet.
Behind the scenes, the JSONArray object stores the json data in an ArrayList<Object>, and it has a method called toList(). There's absolutely no need to loop through the JSONArray in order to set values in the array. The simpler code would look something like this
String data = "{\"data\":[\"str1\", \"str2\", \"str3\"]}";
JSONObject json = new JSONObject(data);
List<Object> list = json.getJSONArray("data").toList();
System.out.println(myList);
Note: This will create a list of generic Objects. The currently accepted answer doesn't define a type for the List, which is unsafe. It doesn't enforce type safety, and errors will occur at runtime instead of at compile time.
If you want to convert all of the inner objects to a String, you can do this by upcasting the List to an Object, and then casting it to a List<String>. I don't particularly recommend it, but it can be done like this. List<String> list = (List<String>) (Object) json.getJSONArray("data").toList();.
A better way of casting the value to a specific type would be via a stream to call the Object.toString() method.
List<String> list = json.getJSONArray("data").toList().stream().map(Object::toString).collect(Collectors.toList());
or, if you have a specific type you want to cast it to, you can use
List<MyObject> list = json.getJSONArray("data").toList().stream().map(jsonObject -> (MyObject) jsonObject).collect(Collectors.toList());
Finally, as others have pointed out, there are better libraries for dealing with json. Gson is a great library, however I personally prefer Jackson. They both offer similar resources, but I've found that Jackson's ObjectMapper is more customizable and more widely used.

JSON Array parsing where key is missing in the key-value pair

I am trying to parse a JSON Array which looks something like this
"data":["data1","data2","data3"]
If I write JSONArray arr = obj1.getJSONArray("data");, this will provide me with the JSON array but since the key name from key-value pair is missing, how will I retrieve "data1", "data2" and "data3"?
JSON arrays allows for non json children. In this case, the children are of String value:
for(int i=0;i<arr.length();i++) {
String value = arr.getString(i);
}
My syntax might be inaccurate
Assuming this is your JSON,
{"data":["data1","data2","data3"]}
Use the following to retrieve the array,
JSONArray arrJson = jsonData.getJSONArray("data");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++) {
arr[i] = arrJson.getString(i);
}

how to get two string array item position and store in each separate string array in android

Sorry for my bad English. I am using two separate string array for each item of arraylist. All things working fine . My Question is I want to take each item of String array (say) if i take string array "asasaqty" and another item of string array "asasaId" then I want to store each item of string array value in third string array (say:[id1,qty1] and so on). Please let me know if there is a proper solution for this.
Below is my code.
Thanks in advance
String [] asasaqty;
String [] asasaId;
final AddToCartData addToCartData = response.body();
shoppingBagArrayList = addToCartData.getData();
asasaqty = new String[shoppingBagArrayList.size()];
asasaId = new String[shoppingBagArrayList.size()];
for (int i = 0; i < shoppingBagArrayList.size(); i++) {
asasaqty[i] = shoppingBagArrayList.get(i).getQty();
asasaId[i]=shoppingBagArrayList.get(i).getProductId();
System.out.println("==========wwwww========"+ Arrays.toString(asasaqty));
System.out.println("======wwwwssssswwwwss======"+ Arrays.toString(asasaId));
/* HashMap<String,String> map=new HashMap<String,String>();
for (int i = 0; i < asasaqty.length; i++) {
map.put(asasaqty[i],asasaId[i]);
System.out.println("======aaaaaaa======"+ map.put(asasaqty[i],asasaId[i]));
}*/
After printing the value in logcat the value is looking like
/System.out: ==========wwwww========[3, 2]
/System.out: ======wwwwssssswwwwss======[151, 10]
Now i want to take another String array and store each item asasaqty and asasaId in separate array like below
String[] xyz = [3,151] and
String[] abc = [2,10]
Please let me know how can we do this.
You can use productID and key (Assuming it is unique) and qty as value.
HashMap<Integer,Integer> dataMap = new HashMap<>();
for (int i=0; i <shoppingBagArrayList.size; i++){
dataMap.put(shoppingBagArrayList.get(i).getProductId() , shoppingBagArrayList.get(i).getQty());
}
System.out.println("DataMap: "+dataMap);

How to get element in 2d Java ArrayList?

I have converted a json string into a java arraylist and I'm looking to access a specific element.
.get(0).get(2) for example doesn't work as I found on another question.
When I use .get(0) I get the following reposnse:
[{ID=d224fe6b2d35728bbb9c9132db015ba0, Name=dl, DisplayName=Sneakers,
MatchTypes=[object], Score=1.0,
PassParams=reqID=MjAxOC0wMy0wMSAxNTowNTo0MS40NTcwNzM4MTMgKzAwMDAgVVRDIG09Kzc2MzIwNi45ODYzODkxNDZfXzA0MTgyMWEyNDg5MjZhNTZiLTYwYjBjNzA0ZDQ0NF9KaWtLTQ==}
So it looks like the arraylist is a list of lists.
I'm looking to access the DisplayName value
The only code I have has been to convert the json string and the attempt at accesing arraylist:
public void setJson(String jsonString) {
Gson googleJson = new Gson();
ArrayList array = googleJson.fromJson(jsonString, ArrayList.class);
String keyword = array.get(0).get(2).toString();
}
Any help is much appreciated!
nested for loops to exhausted search is the easiest way for beginners; for example
for (int I = 0; I < array.length; I++)
{
for (int j = 0; j < array.length; j++)
{
}
}
then do an if else statement to return the statement you want; and give you the location.

JSON Array iteration in Android/Java

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

Categories