簡體   English   中英

REST無需寫入和讀取文件即可返回JSONObject

[英]REST return to JSONObject without writing and reading a file

我下面的以下代碼可以正常工作,並且可以很好地完成工作。 但是我真正想做的是進行REST調用,進行內部解析(如果需要),然后從那里獲取/應用我的JSONObject值,而不必先將JSON返回結果寫入文本文件。 基本上,我希望在處理過程中不必從文本文件中寫入和讀取JSON即可獲得相同的結果。

似乎有幾種選擇可以做到這一點。 但是到目前為止,我沒有嘗試過任何工作,也沒有超出我的理解范圍。 在我不知道的當前庫中,也可能對此進行了簡單的修復。 向我展示如何更改代碼以實現此目標的任何幫助將不勝感激。

碼:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Account {

public static void main(String[] args) {
    File f = new File(
            "/Users/name/restLog.txt");
    if (!f.exists()) {
        try {
            f.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    try {
        FileOutputStream fos = new FileOutputStream(f);
        TeeOutputStream myOut = new TeeOutputStream(System.out, fos);
        PrintStream ps = new PrintStream(myOut);
        System.setOut(ps);
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        // create HTTP Client
        HttpClient httpClient = HttpClientBuilder.create().build();
        // create new getRequest
        HttpGet getRequest = new HttpGet(
                "http://www.asite.com");
        HttpResponse response = httpClient.execute(getRequest);
        // check 200 response was successful
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }
        // Get-Capture Complete application/JSON body response
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (response.getEntity().getContent())));
        String output;
        // Simply iterate through JSON response and show on console.
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            JSONParser parser = new JSONParser();
            Object obj = parser
                    .parse(new FileReader(
                            "/Users/name/restLog.txt"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject accountObject = (JSONObject) jsonObject
                    .get("account");
            String email = (String) accountObject.get("email");
            Long id = (Long) accountObject.get("id");
            System.out.println("My id is " + id);
            System.out.println("My email is " + email);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

}

您必須實現自己的對象模型,才能使用ObjectMapper解析響應:

ObjectMapper mapper = new ObjectMapper();
YourObject object = mapper.readValue(response.getEntity().getContent());

該對象必須包含JSON注釋字段,例如:

@JsonProperty("userName")
private String userName;

然后,您可以為您的字段生成getter / setter對。 如果json屬性是json數組,則必須創建一個Java列表對象。 如果您在Java EE中工作,甚至不需要注釋,則映射會發生,而無需注釋字段。 也看看傑克遜

暫無
暫無

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

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