2016-06-28 2 views
0

매핑 된 값을 배열에 배치하는 방법과 해당 배열을 반복하는 방법을 이해하는 것이 정말 힘듭니다.Jackson JSON에서 Java로 값을 저장하는 방법

test.json

[ 
    { 
    "Name": "Bob", 
    "Nationality": "", 
    "City": "Chicago", 
    "Phone" : "451232424234" 
    }, 

    ......continues with more objects 
] 

testTemplate.java

//imports 
    @JSONInclude(Json.Include.Non_NULL) 
    @JsonPropertyOrder({"Name,"Nationality","City","Phone"}) 

    Public class testTemplate { 

    @JsonProperty("Name") 
    private String userName; 

    @JsonProperty("Nationality") 
    private String nation; 

    @JsonProperty("City") 
    private String city; 

    @JsonProperty("Phone") 
    private String phone; 

    @JsonProperty("Name") 
    public String getName (String userName) { 
     this.userName = userName; 
    } 

    @JsonProperty("Nationality") 
    public String nation (String nation) { 
     this.nation = nation; 
    } 

    @JsonProperty("City") 
    public String city (String city) { 
     this.city = city; 
    } 

    @JsonProperty("Phone") 
    public String phone (String phone) { 
     this.phone = phone; 
    } 

    public String toString() { 
    return ToStringBuilder.reflectionToString(this); 
    } 

testParse.java 내가 어떻게 코드가 일을 정확히 명확히 첫번째 돕고, 필요

Public Class testParse { 
    List<testParse> test; 
    ObjectMapper mapper; 

    protected void setUp() throws IOException { 
      mapper = new ObjectMapper(); 
      mapper.enable(SerializationFeature.INDENT_OUTPUT(); 
      test = mapper.readValue(this.getClass().getResourcesAsStream("test.json"), 
      mapper.getTypeFactory().constructCollectionType(List.class, testParse.class)); 

JSON 속성 (이름, 국적, 도시, 전화)을 Java에 넣습니다.

필자는 testTemplate 파일을 사용하여 속성을 보관할 문자열을 만든 다음 testParse 파일에 json을 통해 읽은 "test"(배열로?)

내 목표는 testParse에 있습니다. 모든 것이 "테스트"에있는 경우, 그 내용을 읽은 다음이를 꺼내서 folderList에 넣기 시작합니다.

public static Map<String, String> userName throws IOException { 
    Map<String, String> folderList = new TreeMap<>(); 
    //Don't know how, but iterate through "test" 
    LineIterator it = new LineIterator(//the method used to read the json file); 
    try { 
     while(it.hasNext()) { 
     String line = it.nextLine(); 
     folderList.put(userName,nation) //can I also put city and phone at once as well or should I create another put: folderList.put(userName, city) 
     return folderList; 

어떻게하면됩니까? jackson 매퍼를 사용한 후에 json의 속성을 folderList에 넣는 더 좋은 방법이 있습니까?

답변

1

사실, testTemplate은 아무것도 생성하지 않습니다. Jackson이 여기에서 한 것은 "test.json"의 데이터를 String으로 가져온 다음 Reflection을 사용하여 testTemplate.java의 형식을 읽는 것입니다. 템플릿에 기반하여 ObjectMapper 객체에 추가하는 설정 만 있습니다. Jackson은 test.json을 객체 Java 배열로 변환합니다.
P/S : 두 속성에 주석을 추가 할 필요가 없으며 POJO 클래스의 함수를 가져올 필요가 없습니다. 함수 또는 속성 만 가져 오면 잭슨에 충분합니다.

+0

testParse.java의 folderList 배열에 객체를 추가하는 방법을 보여줄 수 있습니까? – Bobshark

+0

당신이 그것을 따라 그것을 얻을 수 http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects –