如何使用Java中的bufferReader在json对象中获取特定元素

时间:2019-11-06 16:41:40

标签: java json

我有通过Java Jason.Helpers.json_map请求获取的JSON``数据。

我需要计算JSON对象中有多少个GET对象大于50。

现在,我只是使用age逐行获取整个JSON数据,但是如何获取JSON对象中的单个元素bufferreader并将其与数字50进行比较?

age

对于JSON数据的示例响应,我需要将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()); } } 值作为age

integer

3 个答案:

答案 0 :(得分:1)

您将需要一个像杰克逊这样的json库

  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) {

您必须将json映射到类或使用更多的基本json api阅读节点

供参考 https://java2blog.com/jackson-example-read-and-write-json/

答案 1 :(得分:0)

您可以使用JacksonGson等最受欢迎的JSON库中的任何一个来解析键data的值,然后可以将问题缩小到如何计算值字符串中值大于50的年龄?

代码段

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

控制台输出

  

2

答案 2 :(得分:0)

没有任何JSON库,请尝试以下代码

WebRequest请求= WebRequest.Create(“ https://coderbyte.com/api/challenges/json/age-counting”); WebResponse响应= 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();

//最终输出将为128