jeudi 16 novembre 2017

Method for parsing json data from an API

So I have an API project that sends back some JSON data, and depending on which call this data can be formatted in a number of different ways.

Is the correct way to do this to always return data in the same type (like a Collection ) or is to write a method on the non API application using reflection?

Here is my current method for parsing that data, but it won't work if the JSON data doesn't lend itself to being a Collection:

public static Collection<Map> sendPostRequest(String requestURL)
{
  StringBuffer jsonString;

try {
  URL url = new URL(requestURL);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  connection.setDoInput(true);
  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Accept", "application/json");
  connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");

  BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  jsonString = new StringBuffer();
  String line;
  while ((line = br.readLine()) != null) {
    jsonString.append(line);
  }
  br.close();
  connection.disconnect();

} catch (Exception e) {
  throw new RuntimeException(e.getMessage());
}

Gson gson = new Gson();

Type collectionType = new TypeToken<Collection<Map>>(){}.getType();
Collection<Map> dataCollection = gson.fromJson(jsonString.toString(), collectionType);

return dataCollection;
}

I hope this questions isn't too open ended, but just need some logistical/best practices help





Aucun commentaire:

Enregistrer un commentaire