programing

Java(Jackson)를 사용하는 JSON에서 중첩된 키 값을 읽는 중입니다.

telecom 2023. 3. 26. 09:38
반응형

Java(Jackson)를 사용하는 JSON에서 중첩된 키 값을 읽는 중입니다.

저는 파이썬에서 온 새로운 자바 프로그래머입니다.네스트된 키가 포함된 JSON으로 수집/반환되는 날씨 데이터가 있는데, 이 상황에서 값을 어떻게 끌어낼지 모르겠습니다.이 질문은 전에도 한 번 해본 적이 있을 텐데, 맹세코 구글을 많이 검색해서 답을 찾을 수 없을 것 같아요.지금은 json-simple을 사용하고 있습니다만, Jackson으로 바꾸려고 해도 방법을 찾을 수 없었습니다.Jackson/Gson이 가장 많이 사용되는 라이브러리인 것 같기 때문에, 그 라이브러리 중 하나를 사용한 예를 보고 싶습니다.아래는 제가 지금까지 작성한 코드와 데이터 샘플입니다.

{
    "response": {
        "features": {
            "history": 1
        }
     },
    "history": {
        "date": {
            "pretty": "April 13, 2010",
            "year": "2010",
            "mon": "04",
            "mday": "13",
            "hour": "12",
            "min": "00",
            "tzname": "America/Los_Angeles"
        },
        ...
    }
}

주요 기능

public class Tester {

    public static void main(String args[]) throws MalformedURLException, IOException, ParseException {
        WundergroundAPI wu =  new WundergroundAPI("*******60fedd095");

        JSONObject json = wu.historical("San_Francisco", "CA", "20100413");

        System.out.println(json.toString());
        System.out.println();
        //This only returns 1 level. Further .get() calls throw an exception
        System.out.println(json.get("history"));
    }
}

'historical' 함수는 JSONObject를 반환하는 다른 함수를 호출합니다.

public static JSONObject readJsonFromUrl(URL url) throws MalformedURLException, IOException, ParseException {

    InputStream inputStream = url.openStream();

    try {
        JSONParser parser = new JSONParser();
        BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));

        String jsonText = readAll(buffReader);
        JSONObject json = (JSONObject) parser.parse(jsonText);
        return json;
    } finally {
        inputStream.close();
    }
}

Jackson의 트리 모델(JsonNode두 가지 접근 방식('get')을 모두 사용할 수 있습니다.null결측값 및 "안전한" 액세스 장치('패스')를 사용하여 "경로' 노드를 통과할 수 있습니다.예를 들어 다음과 같습니다.

JsonNode root = mapper.readTree(inputSource);
int h = root.path("response").path("history").getValueAsInt();

지정된 경로에서 값을 반환하거나 경로가 없는 경우 0(기본값)을 반환합니다.

그러나 보다 편리하게 JSON 포인터 식을 사용할 수 있습니다.

int h = root.at("/response/history").getValueAsInt();

다른 방법도 있습니다.또한 구조를 실제로 POJO(Plain Old Java Object)로 모델링하는 것이 편리합니다.컨텐츠는 다음과 같은 경우에 적합합니다.

public class Wrapper {
  public Response response;
} 
public class Response {
  public Map<String,Integer> features; // or maybe Map<String,Object>
  public List<HistoryItem> history;
}
public class HistoryItem {
  public MyDate date; // or just Map<String,String>
  // ... and so forth
}

이 경우 Java 개체와 마찬가지로 결과 개체를 이동할 수 있습니다.

Jsonpath 사용

정수 h = JsonPath.parse(json).read("$response.repository.history", Integer.class);

잭슨의 ObjectMapper를 보세요.클래스를 만들어 JSON을 모델링한 후 ObjectMapper의 readValue 메서드를 사용하여 JSON 문자열을 모델 클래스의 인스턴스로 '직렬화'할 수 있습니다.그리고 그 반대입니다.

jpath API를 사용해 보십시오.JSON Data의 xpath 등가입니다.JSON 데이터를 통과하고 요청된 값을 반환하는 jpath를 제공하여 데이터를 읽을 수 있습니다.

이 Java 클래스는 구현이며 API 호출 방법에 대한 예제 코드가 있습니다.

https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java

리드미 -

https://github.com/satyapaul/jpath/blob/master/README.md

예:

JSON 데이터:

{
    "data": [{
        "id": "13652355666_10154605514815667",
        "uid": "442637379090660",
        "userName": "fanffair",
        "userFullName": "fanffair",
        "userAction": "recommends",
        "pageid": "usatoday",
        "fanPageName": "USA TODAY",
        "description": "A missing Indonesian man was found inside a massive python on the island of Sulawesi, according to local authorities and news reports. ",
        "catid": "NewsAndMedia",
        "type": "link",
        "name": "Indonesian man swallowed whole by python",
        "picture": "https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQBQf3loH5-XP6hH&w=130&h=130&url=https%3A%2F%2Fwww.gannett-cdn.com%2F-mm-%2F1bb682d12cfc4d1c1423ac6202f4a4e2205298e7%2Fc%3D0-5-1821-1034%26r%3Dx633%26c%3D1200x630%2Flocal%2F-%2Fmedia%2F2017%2F03%2F29%2FUSATODAY%2FUSATODAY%2F636263764866290525-Screen-Shot-2017-03-29-at-9.27.47-AM.jpg&cfs=1&_nc_hash=AQDssV84Gt83dH2A",
        "full_picture": "https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQBQf3loH5-XP6hH&w=130&h=130&url=https%3A%2F%2Fwww.gannett-cdn.com%2F-mm-%2F1bb682d12cfc4d1c1423ac6202f4a4e2205298e7%2Fc%3D0-5-1821-1034%26r%3Dx633%26c%3D1200x630%2Flocal%2F-%2Fmedia%2F2017%2F03%2F29%2FUSATODAY%2FUSATODAY%2F636263764866290525-Screen-Shot-2017-03-29-at-9.27.47-AM.jpg&cfs=1&_nc_hash=AQDssV84Gt83dH2A",
        "message": "Akbar Salubiro was reported missing after he failed to return from harvesting palm oil.",
        "link": "http:\/\/www.usatoday.com\/story\/news\/nation-now\/2017\/03\/29\/missing-indonesian-man-swallowed-whole-reticulated-python\/99771300\/",
        "source": "",
        "likes": {
            "summary": {
                "total_count": "500"
            }
        },
        "comments": {
            "summary": {
                "total_count": "61"
            }
        },
        "shares": {
            "count": "4"
        }
    }]

}

코드 조각:

String jPath = "/data[Array][1]/likes[Object]/summary[Object]/total_count[String]";

String value = JSONDataReader.getStringValue(jPath, jsonData);

언급URL : https://stackoverflow.com/questions/29858248/reading-value-of-nested-key-in-json-with-java-jackson

반응형