寻找一种解析JSON的简单方法

时间:2014-12-07 21:00:01

标签: java json parsing

我试图使用Java解析以下JSON:

{ "student_id": "123456789", "student_name": "Bart Simpson", "student_absences": 1}

实现这一目标的最简单方法是什么。我尝试按照下面的方式进行,但认为必须有一个更简单的方法。

 import org.json.*
 JSONObject obj = new JSONArray("report");

 for(int i = 0; I < arr.length(); i++){
     String studentname =     
         arr.getJSONObject(i).getString("student_id");
         arr.getJSONObject(i).getString("student_name");
         arr.getJSONObject(i).getString("student_name");
 }

2 个答案:

答案 0 :(得分:2)

Gson

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

public class Main {
  public static void main(String[] args) {
    String json = "{ \"student_id\": \"123456789\", \"student_name\": \"Bart Simpson\", \"student_absences\": 1}";
    Student student = new Gson().fromJson(json, Student.class);
    System.out.println(student);
  }
}

class Student {

  @SerializedName("student_id")
  String studentId;

  @SerializedName("student_name")
  String studentName;

  @SerializedName("student_absences")
  Integer studentAbsences;

  @Override
  public String toString() {
    return "Student{" +
      "studentId='" + studentId + '\'' +
      ", studentName='" + studentName + '\'' +
      ", studentAbsences=" + studentAbsences +
      '}';
  }
}

另一个受欢迎的是Jackson

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
  public static void main(String[] args) throws Exception {
    String json = "{ \"student_id\": \"123456789\", \"student_name\": \"Bart Simpson\", \"student_absences\": 1}";
    Student student = new ObjectMapper().readValue(json, Student.class);
    System.out.println(student);
  }
}

class Student {

  @JsonProperty("student_id")
  String studentId;

  @JsonProperty("student_name")
  String studentName;

  @JsonProperty("student_absences")
  Integer studentAbsences;

  @Override
  public String toString() {
    return "Student{" +
      "studentId='" + studentId + '\'' +
      ", studentName='" + studentName + '\'' +
      ", studentAbsences=" + studentAbsences +
      '}';
  }
}

在这两种情况下,运行Main都会打印:

Student{studentId='123456789', studentName='Bart Simpson', studentAbsences=1}

修改

如果不创建Student课程,您可以试试JsonPath之类的内容。

答案 1 :(得分:0)

您问题的答案取决于您想要达到的目标。您的示例将生成一个字符串数组。前面的答案导致Java类具有每个字段的属性。另一种选择是将值放入地图中。

如果为此编写了编码器/解码器组合。编码非常简单:使用地图的键和值。解码器(要映射的JSON字符串或其他任何东西)需要一个解析器(最好是一个标记器)。