繁体   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