您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中解析 JSON 时,为了避免类型转换错误,可以使用一些流行的 JSON 库,如 Jackson、Gson 或 org.json
首先,将 Jackson 依赖项添加到项目的 pom.xml 文件中:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
然后,使用 ObjectMapper 类解析 JSON 字符串:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
private String city;
// Getters and setters
}
首先,将 Gson 依赖项添加到项目的 pom.xml 文件中:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
然后,使用 Gson 类解析 JSON 字符串:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
private String city;
// Getters and setters
}
首先,将 org.json 依赖项添加到项目的 pom.xml 文件中:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
然后,使用 JSONObject 类解析 JSON 字符串:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
JSONObject jsonObject = new JSONObject(jsonString);
Person person = new Person();
person.setName(jsonObject.getString("name"));
person.setAge(jsonObject.getInt("age"));
person.setCity(jsonObject.getString("city"));
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
private String city;
// Getters and setters
}
这些方法都可以避免类型转换错误,因为它们会自动将 JSON 数据转换为相应的 Java 对象。只需确保在解析 JSON 时使用正确的数据类型即可。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。