gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:10:55 25 4
gpt4 key购买 nike

我正在尝试使用 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");
}

最佳答案

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 之类的东西。

关于java - 寻找一种简单的方法来解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27347763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com