0

我有以下程序,它解析 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;
    }


}
4

5 回答 5

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");
}
于 2013-04-25T10:26:44.977 回答
1

还有双括号初始化:

List<String> finalSymbolsList = new ArrayList<String>() {{
    add("DYY");
    add("LIIO");
    add("AFD");
    add("XCF");
}}
于 2013-04-25T10:29:27.710 回答
0
List<String> places = Arrays.asList("DYY" , "LIIO" , "AFD" , "XCF") 
于 2013-04-25T10:27:27.660 回答
0

只需在构造函数中填写列表

public JsonDTO() {
    mySymbols.addAll(finalSymbolsList);
}
于 2013-04-25T10:29:23.280 回答
0

另一种选择是

 List<String> finalSymbolsList = new ArrayList<String>();
 Collections.addAll(finalSymbolsList ,"DYY" , "LIIO" , "AFD" , "XCF" );
于 2013-04-25T10:29:54.233 回答