簡體   English   中英

使用 Java Spring Boot 獲取 Json 項的值

[英]Get the value of items of a Json with Java Spring Boot

我正在嘗試從下面的 Json 文件中提取 API 數據。 我想檢索每個“項目”的“名稱”。

檢索到“名稱”后,我想創建一個新的 Json,其中將包含:{name: "toto", name: "titi"....}

然后目標是在我這邊創建一個 API,它在來自http://localhost/getitems的調用中將返回創建的 Json 的結果。

我是 Java 和 Spring Boot 的新手,所以如果您認為有更簡單的代碼,請告訴我,我希望您能幫助我輕松創建新的 Json 文件。 謝謝 !

// Json File (it has been reduced, more than 700 name are present)
{
    "kind": "Space",
    "apiVersion": "v1",
    "metadata": {
        "selfLink": "something",
        "resourceVersion": "something"
    },
    "items": [
        {
            "metadata": {
                "name": "projet1"                
            }
        },
        {
            "metadata": {
                "name": "com-cicd"
             }   
        }
    ]
}

// TestGet.java Class
public static NameSpaceJson getPostWithCustomHeaders(String DebutUrl, String MilieuUrl, String ParamUrl) {
        String url = DebutUrl.concat(MilieuUrl).concat(ParamUrl);
        String Bearer = "...";


        // create headers & template
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();

        // set `accept` header for the type of response
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        // set custom header, bearer here too
        headers.set("x-request-source", "desktop");
        headers.set("Authorization", "Bearer "+Bearer);

        // build the request
        @SuppressWarnings({ "rawtypes", "unchecked" })
        HttpEntity request = new HttpEntity(headers);

        // use `exchange` method for HTTP call, this one permits us to use bearer for auth
        ResponseEntity<NameSpaceJson> response = restTemplate.exchange(url, HttpMethod.GET, request, NameSpaceJson.class, 1);
        if(response.getStatusCode() == HttpStatus.OK) {
            return response.getBody();
        } else {
            return null;
        }
    }
// The name in the same file
public static void main(String[] args) {
        TestGet.disableSSLCertificateChecking();
        NameSpaceJson resultresponse = getPostWithCustomHeaders("https...","api","names");
//      Long response = resultresponse.getValue().getId();
        List<Item> response = resultresponse.getItems();

        String test = GenerateNewJsonNameSpace.createJsonContent(response);


        System.out.println(test);
    }
//NameSpaceJson.java File
package com.example.consumingrest;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class NameSpaceJson {

    private String kind;
    private String apiVersion;
    private List<Item> items;

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public String getApiVersion() {
        return apiVersion;
    }

    public void setApiVersion(String apiVersion) {
        this.apiVersion = apiVersion;
    }

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }
}
//Metadata.java
package com.example.consumingrest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Metadata {

    private String name;
    private String creationTimestamp;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCreationTimestamp() {
        return creationTimestamp;
    }

    public void setCreationTimestamp(String creationTimestamp) {
        this.creationTimestamp = creationTimestamp;
    }
}
//Item.java
package com.example.consumingrest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Item {

    Metadata metadata;

    public Metadata getMetadata() {
        return metadata;
    }


    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }
}
// GenerateNewJsonNameSpace ( this is what i have tried.. but i'm sure we can do really better.. )
package com.example.consumingrest;

import java.util.List;

public class GenerateNewJsonNameSpace { 

    public static String createJsonContent(List<Item> ListOfNameSpace) {

        if(ListOfNameSpace.isEmpty()) {
            return null;
        }else {     
        String LeJson;
        LeJson = "{";
        for(int i = 0; i < ListOfNameSpace.size(); i++) {
            LeJson.concat(ListOfNameSpace.get(i).getMetadata().getName());
            LeJson.concat(", \n");
        }
        LeJson.concat("}");
        return LeJson;
        }


    }
}

您可以使用名為 Gson 的庫,該庫由 google 創建,專門用於處理 JSON 數據。

您需要做的就是創建一個新的 Gson 對象並用它解析 JSON。 您只需幾行即可完成

String jsonString = "{ \\"kind\\": \\"Space\\", \\"apiVersion\\": \\"v1\\", \\"metadata\\": { \\"selfLink\\": \\"something\\", \\"resourceVersion\\": \\"something\\" }, \\"items\\": [ { \\"metadata\\": { \\"name\\": \\"projet1\\" } }, { \\"metadata\\": { \\"name\\": \\"affeccom-cicd\\" } } ] }";

    JsonObject data = new Gson().fromJson(jsonString, JsonObject.class);
    JsonArray names = data .get("items").getAsJsonArray();
    for(JsonElement element : names){
        JsonObject object = element.getAsJsonObject();
        System.out.println(object.get("metadata").getAsJsonObject().get("name").getAsString());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM