Java中json格式的数据使用

本文深入讲解了Java中使用阿里FastJSON库进行JSON数据处理的方法,包括JSONArray和JSONObject的基本用法,以及通过ObjectMapper实现对象到JSON字符串的序列化过程。
ⅠJSONArray

链接:Java中找jar包的一个网站
1
这里我们需要导入这个阿里的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"}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值