简体   繁体   中英

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. 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.

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 mapper = new ObjectMapper();
YourObject object = mapper.readValue(response.getEntity().getContent());

This object has to contain JSON annotated fields like:

@JsonProperty("userName")
private String userName;

Then you can generate getter/setter pair for your fields. If the json property is a json array then you have to create a java list object. If you work in Java EE you even do not need the annotations, the mapping happens without the need to annotate the fields. Also have a look at Jackson .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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