我是java编程的初学者。
如何通过填充for循环中每个索引的值来创建和初始化包含Arraylist或数组中的单维和二维数组的数组。任何帮助将不胜感激
{
"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",
}
}
我们的想法是创建一个存储人们信息的数组,如上所示
答案 0 :(得分:1)
您可以使用Java为您的数据创建和初始化2D数组。
String[][] array = new String[][]{
{"john","20","blue","somewhere in the world","degree"},
{"ben","16", "green", "somewhere in the world", "secondary school"}
};
但对于您的数据,最好有一些数据结构,如下所示。
<强> 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
}
主要功能
List<Person> personsList = new ArrayList<>();
// loop starts
PersonDetails pd = new PersonDetails();
//set values
Person p = new Person();
//set values
personsList.add(p);
//loop ends
答案 1 :(得分:0)
答案 2 :(得分:0)
您的JSON语法错误,正确的方法是获取像这样的json
{
"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"
}
]
}
[
和]
定义了一个元素数组,{
和}
代表了数据类型的对象;在这种情况下,人们。
然后你可以获得一系列'people'对象,其中包含必要的信息。我有this将java对象序列化和反序列化为json和visceversa,试试这个。希望能帮到你。