0

I have the following program , which parses the JSON and forms an ArrayList as shown .

How can i initialze the mySymbols ArrayList here , so that it always consists of some predefined symbols every time

There are Four Predefined Symbols namely ("DYY" , "LIIO" , "AFD" , "XCF" ) , so that it will be always part of finalSymbolsList

I can achieve this manually by doing this step

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;
    }


}

5 Answers 5

1

try this

new String[] {"One","Two","Three","Four"} 
or

List<String> places = Arrays.asList("One", "Two", "Three") 

or write a constructor

public ClassName()
{
  list = new ArrayList<String>();
  list .add("ONE");
  list .add("TWO");
  list .add("THREE");
  list .add("FOUR");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Also the double brace initialization:

List<String> finalSymbolsList = new ArrayList<String>() {{
    add("DYY");
    add("LIIO");
    add("AFD");
    add("XCF");
}}

Comments

0
List<String> places = Arrays.asList("DYY" , "LIIO" , "AFD" , "XCF") 

Comments

0

just fill the list in the constructor

public JsonDTO() {
    mySymbols.addAll(finalSymbolsList);
}

Comments

0

Another alternative will be

 List<String> finalSymbolsList = new ArrayList<String>();
 Collections.addAll(finalSymbolsList ,"DYY" , "LIIO" , "AFD" , "XCF" );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.