Java API call Example using GSON, org.json.json and Jackson [ Simple Get Call] and parsing result as JSON
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class APICALL {
public static void main(String[] args) throws IOException {
// String url="https://mocki.io/v1/19a50724-c2e5-46a1-b457-543462cdfde2";
String url="https://jsonplaceholder.typicode.com/users";
String line;
StringBuilder resp=new StringBuilder();
System.out.println(url);
HttpURLConnection con= (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept","application/json");
System.out.println(con.getResponseMessage());
System.out.println(con.getContentType());
InputStream inputStream=con.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
while ((line=reader.readLine())!=null)
{
resp.append(line);
}
System.out.println(resp.toString());
System.out.println("Outputsss");
FileOutputStream fileOutputStream=new FileOutputStream("resp.txt");
fileOutputStream.write(resp.toString().getBytes());
System.out.println("==================Using org.json.json ================== ");
JSONArray jsonArray=new JSONArray(resp.toString());
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
System.out.println(jsonObject.get("name")+"--"+jsonObject.get("email"));
}
System.out.println("Printed total "+jsonArray.length());
System.out.println("==================Using Jackson methods==================");
JsonNode jsonNode=new ObjectMapper().readTree(resp.toString());
jsonNode.forEach(x-> System.out.println(x.get("name")+"--"+x.get("email")));
// using GSOn
System.out.println("==================Using Gson==================");
JsonElement jsonElement=JsonParser.parseString(resp.toString());
JsonArray jar=jsonElement.getAsJsonArray();
for (int i=0;i<jar.size();i++)
{
JsonObject jsonObject=jar.get(i).getAsJsonObject();
System.out.println(jsonObject.get("name")+"--"+jsonObject.get("email"));
}
System.out.println("Printed total "+jar.size());
}
}
Comments
Post a Comment
share your thoughts ....