Gson을 사용하여 JSON 배열을 java.util.List로 구문 분석

다음 내용 의 JsonObject이름 "mapping"이 있습니다.

{
    "client": "127.0.0.1",
    "servers": [
        "8.8.8.8",
        "8.8.4.4",
        "156.154.70.1",
        "156.154.71.1"
    ]
}

다음 "servers"과 같이 배열 을 얻을 수 있다는 것을 알고 있습니다 .

mapping.get("servers").getAsJsonArray()

그리고 지금은 그 구문을 분석 할 JsonArrayjava.util.List

이를 수행하는 가장 쉬운 방법은 무엇입니까?



답변

가장 쉬운 방법은 Gson의 기본 구문 분석 기능을 사용하는 것 fromJson()입니다.

당신이 어떤으로 직렬화해야하는 경우에 적합한이 기능의 구현이있다 ParameterizedType(예를 들어, 어떤 List이다) fromJson(JsonElement json, Type typeOfT).

귀하의 경우에는, 당신은 단지 얻을 필요가 Type의를 List<String>하고 그 다음에 JSON 배열을 구문 분석 Type과 같이 :

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();

List<String> yourList = new Gson().fromJson(yourJson, listType);

귀하의 경우 yourJsonJsonElement이지만 String, any Reader또는 a 일 수도 있습니다 JsonReader.

Gson API 문서를 살펴볼 수 있습니다 .


답변

아래 코드는 com.google.gson.JsonArray. List의 요소와 List의 요소 수를 인쇄했습니다.

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+
            "\"client\":\"127.0.0.1\"," +
            "\"servers\":[" +
            "    \"8.8.8.8\"," +
            "    \"8.8.4.4\"," +
            "    \"156.154.70.1\"," +
            "    \"156.154.71.1\" " +
            "    ]" +
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

산출

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

답변

여기 Gson의 공식 웹 사이트에서 솔루션을 읽었습니다 .

그리고이 코드는 다음과 같습니다.

    String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";

    JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
    JsonArray jsonArray = jsonObject.getAsJsonArray("servers");

    String[] arrName = new Gson().fromJson(jsonArray, String[].class);

    List<String> lstName = new ArrayList<>();
    lstName = Arrays.asList(arrName);

    for (String str : lstName) {
        System.out.println(str);
    }    

모니터에 결과 표시 :

8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1

답변

@SerializedName모든 필드에 대해 사용하는 목록 매핑을 얻을 수있었습니다 Type. 주변 에 논리 가 필요 하지 않았습니다 .

코드 실행- 아래 4 단계 -디버거를 통해 List<ContentImage> mGalleryImages객체가 JSON 데이터로 채워지 는 것을 관찰 할 수 있습니다.

예를 들면 다음과 같습니다.

1. JSON

   {
    "name": "Some House",
    "gallery": [
      {
        "description": "Nice 300sqft. den.jpg",
        "photo_url": "image/den.jpg"
      },
      {
        "description": "Floor Plan",
        "photo_url": "image/floor_plan.jpg"
      }
    ]
  }

2. 목록이있는 Java 클래스

public class FocusArea {

    @SerializedName("name")
    private String mName;

    @SerializedName("gallery")
    private List<ContentImage> mGalleryImages;
}

3. 목록 항목에 대한 Java 클래스

public class ContentImage {

    @SerializedName("description")
    private String mDescription;

    @SerializedName("photo_url")
    private String mPhotoUrl;

    // getters/setters ..
}

4. JSON을 처리하는 자바 코드

    for (String key : focusAreaKeys) {

        JsonElement sectionElement = sectionsJsonObject.get(key);
        FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
    }

답변

로 시작하는 mapping.get("servers").getAsJsonArray()경우 Guava에 액세스 Streams할 수있는 경우 아래 한 줄짜리를 수행 할 수 있습니다.

List<String> servers = Streams.stream(jsonArray.iterator())
                              .map(je -> je.getAsString())
                              .collect(Collectors.toList());

노트 StreamSupportJsonElement유형에 대해 작업 할 수 없으므로 충분하지 않습니다.