0

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

2

1 Answer 1

1
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);
  }


}
Sign up to request clarification or add additional context in comments.

1 Comment

Probably some comments would not hurt understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.