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

时间:2015-05-18 07:46:18

标签: java httpresponse jsonobject

以下代码(下方)可以正常工作并完成工作。但我真正喜欢做的是进行我的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();
    }

}

}

1 个答案:

答案 0 :(得分:0)

您必须实现自己的对象modell才能使用ObjectMapper解析respone,如:

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

此对象必须包含JSON带注释的字段,如:

@JsonProperty("userName")
private String userName;

然后您可以为您的字段生成getter / setter对。如果json属性是json数组,那么你必须创建一个java列表对象。如果您在Java EE中工作,您甚至不需要注释,映射就可以在不需要注释字段的情况下进行。另请查看Jackson