ⅠJSONArray
链接:Java中找jar包的一个网站

这里我们需要导入这个阿里的json包;
JSON格式:主要用来前后端分离,将前后端数据统一起来。
基本用法:
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
JSONArray array = new JSONArray();
JSONObject o1 = new JSONObject();
o1.put("id", 1);
o1.put("cover_image", "/images/1.png");
o1.put("title", "title1");
o1.put("body", "body1");
array.add(o1);
JSONObject o2 = new JSONObject();
o2.put("id", 2);
o2.put("cover_image", "/images/2.png");
o2.put("title", "title2");
o2.put("body", "body2");
array.add(o2);
System.out.println(array.toJSONString());//返回的是字符串
}
}
结果如下:
[{"id":1,
"cover_image":"/images/1.png",
"title":"title1",
"body":"body1"},
{"id":2,
"cover_image":"/images/2.png",
"title":"title2",
"body":"body2"}]
Ⅱ ObjectMapper
生成json字符串,序列化。
Person.java
public class Person {
private int id;
private String name;
private String password;
public Person(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
}
Main.java
public class Main {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person(1, "tom", "123");
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("JsonString: " + jsonString);
}
}
输出结果为:
JsonString: {"id":1,"name":"tom","password":"123"}
本文深入讲解了Java中使用阿里FastJSON库进行JSON数据处理的方法,包括JSONArray和JSONObject的基本用法,以及通过ObjectMapper实现对象到JSON字符串的序列化过程。
461

被折叠的 条评论
为什么被折叠?



