简体   繁体   English

REST无需写入和读取文件即可返回JSONObject

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

The following code I have (below) works and gets the job done just fine. 我下面的以下代码可以正常工作,并且可以很好地完成工作。 But what I'd really like to do is make my REST call, internally parse(if needed), and grab/apply my JSONObject values from there without having to first write my JSON return results to a text file. 但是我真正想做的是进行REST调用,进行内部解析(如果需要),然后从那里获取/应用我的JSONObject值,而不必先将JSON返回结果写入文本文件。 Basically I'd like to get the same result with out having to Write and Read the JSON from a text file in the middle of my process. 基本上,我希望在处理过程中不必从文本文件中写入和读取JSON即可获得相同的结果。

It seems like there are several options to do this. 似乎有几种选择可以做到这一点。 But none I've tried so far work or are out of my grasp of understanding. 但是到目前为止,我没有尝试过任何工作,也没有超出我的理解范围。 There may be a simple fix to this too with in the current libraries that I'm just not aware of. 在我不知道的当前库中,也可能对此进行了简单的修复。 Any help to show me how I could alter my code to accomplish this would be appreciated. 向我展示如何更改代码以实现此目标的任何帮助将不胜感激。

Code: 码:

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();
    }

}

}

You have to implement your own object modell to be able to parse the respone with the ObjectMapper like: 您必须实现自己的对象模型,才能使用ObjectMapper解析响应:

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

This object has to contain JSON annotated fields like: 该对象必须包含JSON注释字段,例如:

@JsonProperty("userName")
private String userName;

Then you can generate getter/setter pair for your fields. 然后,您可以为您的字段生成getter / setter对。 If the json property is a json array then you have to create a java list object. 如果json属性是json数组,则必须创建一个Java列表对象。 If you work in Java EE you even do not need the annotations, the mapping happens without the need to annotate the fields. 如果您在Java EE中工作,甚至不需要注释,则映射会发生,而无需注释字段。 Also have a look at Jackson . 也看看杰克逊

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM