How to get element in 2d Java ArrayList? - java

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.

Related

How can I convert a String array to a different Class ArrayList in Java

I'm trying to figure out how to write logic to convert an array of string into an ArrayList weekday object
String[] weekdays = request.getParameterValues("weekday");
I've made my ArrayList weekday2 the length of my String[] weekdays.
ArrayList<WeekDay> weekdays2 = new ArrayList<WeekDay>(weekdays.length);
I know there is a way to utilize enums, and that's what I'm trying to do.
for (int i = 0; i < weekdays.length; i++) {
weekdays2.add(new WeekDay().valueOf(weekdays2, weekdays));
}
I know I'm definitely missing something.
error:
The method valueOf(Class<T>, String) in the type Enum<WeekDay> is not applicable for the arguments (ArrayList<WeekDay>, String[])
Code to get list of WeekDay may be such:
for (int i = 0; i < weekdays.length; i++) {
weekdays2.add(WeekDay.valueOf(weekdays[i]));
}

JAVA Get each value of arraylist

I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}

get a Json value without string key - Java JSONObject

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

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

JSON for Java, Encode a JSON array - Streaming

[I have some code to create a JSON array. In this code I am passing some values to x, y, z in a loop which looks like this.
JSONArray list = new JSONArray();
String jsonText = null;
for (int j = 0; j < 4; j++) {
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
jsonText = list.toString();
}
System.out.print(jsonText);
This gives output as
[1234,245,10,312,234,122,1234,67788,345,235,001,332]
How can I get these values in a single array like this?
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]] ] I got the answer for this question needs answer for the below question.
I used one of the below solutions.
Thanks for the response from you guys.
Now i got JSON formate nested Arrays which looks like this
[
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]],
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,3450]],
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,34534]]]
SO i have One big Array which contains three arrays(this can be 2 or more than three arrays sometimes) and each of these three array contains some arrays, in this above example
what is the reverse procedure ? i mean what if i want those values from these arrays. In the same way how i have did. using JSON
JSONArray list = new JSONArray();
list.get() this get method will give me what i requies ?
I used the org.json Java API.
Thanks friends for helping me till now.
Just put it in another JSONArray.
JSONArray array = new JSONArray();
array.add(list);
String jsonText = array.toString();
Update: as per your comment:
Sorry, the output is something like this
[1234,245,10,312,234,122,1234,67788,345,235,001,332]
Can you please tell how to get the above output like this
[1234,245,10][312,234,122][1234,67788,345][235,001,332]
Several ways:
Concatenate to the jsonString.
String jsonText = ""; // Start with empty string.
for (int j = 0; j < 4; j++) {
JSONArray list = new JSONArray(); // Create new on each iteration.
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
jsonText += list.toString(); // += concatenates to existing string.
}
System.out.print(jsonText);
Since String concatenating using += in a loop is memory hogging and slow, rather use StringBuilder.
StringBuilder jsonText = new StringBuilder();
for (int j = 0; j < 4; j++) {
JSONArray list = new JSONArray();
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
jsonText.append(list.toString();
}
System.out.print(jsonText.toString());
I suspect what you want is a syntactically correct JSON array of nested arrays of integers (original post requests invalid JSON). If not, go with #BalusC's answer.
To get an array containing sub-arrays, simply create the sub-arrays as int[] arrays, and add them directly to your main JSONArray.
public int[] getThreeValues() { // example
Random r = new Random();
return new int[] { r.nextInt(100), r.nextInt(100), r.nextInt(100) };
}
public void execute() {
JSONArray master = new JSONArray();
for (int j=0; j<4; j++) {
master.put(getThreeValues());
}
System.out.println(master);
}
Result:
[[3,13,37],[24,4,64],[61,2,1],[97,13,86]]
Note: I'm not sure which JSON library your using, so I used the org.json Java API, which uses put(...) rather than add(...). Also, that particular library supports adding int[] arrays directly to JSONArray - yours may not, in which case you'd need to build the nested JSONArrays and add them to your master.
You can always put the list inside a JSONArray
e.g.
JSONArray list = new JSONArray();
String jsonText = null;
for (int j = 0; j < 4; j++) {
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
}
JSONArray finalList = new JSONArray();
finalList.put(0, list);
jsonText = finaList.toString();
System.out.print(jsonText);
Or (not recommended at all) hack your output,
e.g.
jsonText += "[" + jsonText + "]";
System.out.print(jsonText);

Categories