[英]JAVA How to create single and multi dimensional array
我是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",
}
}
想法是創建一個存儲人員信息的數組,如上所述
您可以像這樣用Java創建和初始化2D數組作為數據。
String[][] array = new String[][]{
{"john","20","blue","somewhere in the world","degree"},
{"ben","16", "green", "somewhere in the world", "secondary school"}
};
但是對於您的數據,最好具有如下所示的一些數據結構。
人.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
您的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”對象數組,以獲取信息。 我有這個序列化和反序列化Java對象為json和visceversa,請嘗試此。 希望對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.