ad fasan
ad fasan

Reputation: 73

how to get a specific element in json object using bufferReader in java

I have JSON`` data I'm getting with java GET request.

I need to count how many age objects are greater than 50 in the JSON object.

Right now I am just getting the whole JSON data line by line using bufferreader, but how do I get the single element age in the JSON object and compare it with the number 50?

package problem;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;
    public class Test {

    public static void main(String args[])
    {
     BufferedReader rd;
     OutputStreamWriter wr;

    try
    {
        URL url = new URL("https://coderbyte.com/api/challenges/json/age-counting");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.flush();

        // Get the response
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
           System.out.println(line);
        }
    }
    catch (Exception e) {
            System.out.println(e.toString());
        }

      }

Sample response for JSON data, I need to get the age value as an integer:

{
   "data":
     "key=IAfpK,
      age=58,
      key=WNVdi,
      age=64,
      key=jp9zt,
      age=47"
}

Upvotes: 4

Views: 12387

Answers (3)

Ravinder Singh
Ravinder Singh

Reputation: 21

Without any JSON libraries, please try following code

WebRequest request = WebRequest.Create("https://coderbyte.com/api/challenges/json/age-counting"); WebResponse response = request.GetResponse();

        //Console.WriteLine("Content length is {0}", response.ContentLength);
        //Console.WriteLine("Content type is {0}", response.ContentType);

        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream();

        // Pipes the stream to a higher level stream reader with the required encoding format.
        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
        string _data = readStream.ReadToEnd();
        var numbers = _data.Split(',');

        var age = numbers.Where(c => c.Contains("age="));
        int _total = 0; 
        foreach (var item in age)
        {
           string _item = item.Replace("\"}", "");
            if (int.Parse(_item.Replace("age=", "")) >= 50){
                _total++;
            }
        }
        //Console.WriteLine(readStream.ReadToEnd());

        Console.WriteLine(_total);
        response.Close();
        readStream.Close();
        Console.ReadLine();

//final output will be 128

Upvotes: 0

LHCHIN
LHCHIN

Reputation: 4009

You can use any one of the most popular JSON libraries such as Jackson or Gson to parse value of the key data, then you can narrow down the problem to How to count how many ages whose value is grater than 50 in the value string?.

Code snippet

String valueStr = "key=IAfpK,age=58,key=WNVdi,age=64,key=jp9zt,age=47";
int count = 0;
for (String part : valueStr.split(",")) {
    String[] subparts = part.split("=", 2);
    if ("age".equals(subparts[0]) && Integer.valueOf(subparts[1]) > 50) {
        count++;
    }
}
System.out.print(count);

Console output

2

Upvotes: 0

Luis Ramirez-Monterosa
Luis Ramirez-Monterosa

Reputation: 2242

You are going to need a json library like jackson

  ObjectMapper mapper =new ObjectMapper();
  try{

   BufferedReader br = new BufferedReader(
     new FileReader(new InputStreamReader(conn.getInputStream())));

   //convert the json string back to object
   Data cdataObj = mapper.readValue(br, Data.class);
   if (cdataObj.age>50) {

you'd have to map the json to a class or use more rudimentary json api reading nodes

for reference https://java2blog.com/jackson-example-read-and-write-json/

Upvotes: 1

Related Questions