rohit kaushik
rohit kaushik

Reputation: 11

Write a java program to get JSON data from URL

1) Write a java program to get JSON data from URL http://echo.jsontest.com/Operand1/10/Operand2/5/Operator/+

2) Perform Mathematical operation in Java after reading JSON from above URL and print result.

example for above URL

Result = 10+5 = 15

3) The result should be dynamic and should change if we change values in above URLs

Upvotes: 0

Views: 5243

Answers (1)

Abhishek Gupta
Abhishek Gupta

Reputation: 11

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Scanner;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {

      InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter the JSON URL :");
      String url = in.next();
    JSONObject json = readJsonFromUrl(url);
    int op1= Integer.parseInt((String)json.get("Operand1"));
    int op2= Integer.parseInt((String)json.get("Operand2"));
    int result = op1+op2;
    System.out.println("Result is : "+ result);
  }


}

Upvotes: 1

Related Questions