Reputation: 57
I am a beginner in java programming.
How do you create and initialize an array which contains a single and two dimensional array like below in an Arraylist or array by populating the value of each indexes within a for loop. any help will be much appreciated
{
"john":
{
"age":"20",
"eye color":"blue",
"location":"somewhere in the world",
"education-level":"degree",
}
"ben" :
{
"age":"16",
"eye color":"green",
"location":"somewhere in the world",
"education-level":"secondary school",
}
}
The idea is to create an array that stores peoples information as seen above
Upvotes: 0
Views: 378
Reputation: 722
You can create and initialize a 2D array in Java like this for your data.
String[][] array = new String[][]{
{"john","20","blue","somewhere in the world","degree"},
{"ben","16", "green", "somewhere in the world", "secondary school"}
};
But for your data it could be better to have some data structure like follows.
Person.java
public class Person{
private String name;
private PersonDetails details;
//getters and setters
}
PersonDetails.java
public class PersonDetails{
private int age;
private String eyeColor;
private String location;
private String educationLevel;
//getters and setters
}
main function
List<Person> personsList = new ArrayList<>();
// loop starts
PersonDetails pd = new PersonDetails();
//set values
Person p = new Person();
//set values
personsList.add(p);
//loop ends
Upvotes: 1
Reputation: 498
Your JSON has a bad syntax, the correct way is get a json like this
{
"people" :
[
{ "name":"john",
"age":"20",
"eye color":"blue",
"location":"somewhere in the world",
"education-level":"degree"
},
{
"name":"ben",
"age":"16",
"eye color":"green",
"location":"somewhere in the world",
"education-level":"secondary school"
}
]
}
The [
and ]
define an array of elements, and the {
and }
represents objects of your data type; in this case people.
Then you can get an array of ´people´ object with the necesary fields for information. I have this to serialize and deserialize java objects to json and visceversa, try this. Hope help you.
Upvotes: 0
Reputation: 111
you can refer to this link:
How to create a Multidimensional ArrayList in Java?
create one multidimensional array list then change the string with T so it will be able to take objects
Upvotes: 0