我有以下程序,它解析JSON并形成一个ArrayList,如图所示。
如何在此处初始化mySymbols ArrayList,以便每次都包含一些预定义符号
有四个预定义符号即(“DYY”,“LIIO”,“AFD”,“XCF”),因此它将始终是finalSymbolsList的一部分
我可以通过执行此步骤手动实现此目的
List<String> finalSymbolsList = jw.getMySymbols();
finalSymbolsList.add("DYY");
finalSymbolsList.add("LIIO");
finalSymbolsList.add("AFD");
finalSymbolsList.add("XCF");
======================
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import com.JsonDTO;
public class Test {
public static void main(String args[]) {
try {
String request = "{\r\n" + " \"mySymbols\": [\r\n"
+ " \"TEST\",\"A\"\r\n" + " ]\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
JsonDTO jw = mapper.readValue(request, JsonDTO.class);
List<String> finalSymbolsList = jw.getMySymbols();
System.out.println(finalSymbolsList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
=======================================
package com;
import java.util.ArrayList;
import java.util.Arrays;
public class JsonDTO {
private ArrayList<String> mySymbols = new ArrayList<String>();
public ArrayList<String> getMySymbols() {
return mySymbols;
}
public void setMySymbols(ArrayList<String> mySymbols) {
this.mySymbols = mySymbols;
}
}
答案 0 :(得分:1)
试试这个
new String[] {"One","Two","Three","Four"}
or
List<String> places = Arrays.asList("One", "Two", "Three")
或写一个构造函数
public ClassName()
{
list = new ArrayList<String>();
list .add("ONE");
list .add("TWO");
list .add("THREE");
list .add("FOUR");
}
答案 1 :(得分:1)
双括号初始化:
List<String> finalSymbolsList = new ArrayList<String>() {{
add("DYY");
add("LIIO");
add("AFD");
add("XCF");
}}
答案 2 :(得分:0)
List<String> places = Arrays.asList("DYY" , "LIIO" , "AFD" , "XCF")
答案 3 :(得分:0)
只需填写构造函数中的列表
public JsonDTO() {
mySymbols.addAll(finalSymbolsList);
}
答案 4 :(得分:0)
另一种选择是
List<String> finalSymbolsList = new ArrayList<String>();
Collections.addAll(finalSymbolsList ,"DYY" , "LIIO" , "AFD" , "XCF" );