您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中处理 JSON 数据,您可以使用一些流行的库,如 org.json
、Jackson
和 Gson
<!-- org.json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println("Name: " + jsonObject.getString("name"));
System.out.println("Age: " + jsonObject.getInt("age"));
System.out.println("City: " + jsonObject.getString("city"));
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
for (int i = 0; i < hobbies.length(); i++) {
System.out.println("Hobby " + (i + 1) + ": " + hobbies.getString(i));
}
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
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("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
private String city;
// Getters and setters
}
import com.google.gson.Gson;
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
}
}
class Person {
private String name;
private int age;
private String city;
// Getters and setters
}
这些示例展示了如何使用不同的库处理 JSON 数据。您可以根据项目需求和个人喜好选择合适的库。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。