Maven工程下:alibaba fastjson2的各种序列化:java对象转json对象、json对象转java对象、json对象转字符串......
·
pom文件导入fastjson2坐标:
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.51</version>
</dependency>
UserVO对象:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVO {
private Long id;
private String userName;
private String name;
private String token;
}
java对象转json对象:
//对象
UserVO userVO = new UserVO(1L,"UserVo","User","0");
//userVo对象:UserVO(id=1, userName=UserVo, name=User, token=0)
System.out.println(userVO);
//java对象转Json
String jsonUserVo = JSONObject.toJSONString(userVO);
//{"id":1,"name":"User","token":"0","userName":"UserVo"}
System.out.println(jsonUserVo);
json对象(json字符串)转java对象:
UserVO userVO1 = JSON.parseObject(JSONObject.toJSONString(userVO),UserVO.class);
//或者
//UserVO userVO1 = JSON.parseObject(jsonUserVo,UserVO.class);
//UserVO(id=1, userName=UserVo, name=User, token=0)
System.out.println(userVO1);
其他:
//java对象转换成json格式的字节码
byte[]bytes=JSON.toJSONBytes(userVO);
//读取字节码
String s = new String(bytes);
//result:{"id":1,"name":"User","token":"0","userName":"UserVo"}
System.out.println(s);
json文件方式+JSONPath:
// json文件:
"MyCar":["AstonMartin","Audio","AUDIOYYDS","AUDIOYYDS2","BENZ","BENZE","BENZYYDS","BMW",
"BMWYYDS","BYD"],
public void testByteJson(){
try ( InputStream fp = new FileInputStream(InfoFiledConstant.JSON_SRC))
{
byte[] bytes = fp.readAllBytes();
// JSONPath path = JSONPath.of("$.MyPhone");
//组装访问的json路径(内容)path
JSONPath path = JSONPath.of("$.MyPhone");
//读取字节码成Json格式
JSONReader parse = JSONReader.of(bytes);
JSONArray extract =(JSONArray) path.extract(parse);
//result:ASUS
System.out.println(extract.get(2));
}catch (Exception e){
e.printStackTrace();
}
}
其他:
static {
try (InputStream is = new FileInputStream(InfoFiledConstant.JSON_SRC)) {
byte[] b = is.readAllBytes();
s = new String(b);
} catch (Exception e) {
System.out.println("ErrorJsonStringRead:" + e.getMessage());
}
}
private static Random r = new Random();
private static String s;
private static String common(String infoConstant) {
String key;
JSONArray common = JSONArray.parse(JSONObject.parseObject(s).get(infoConstant).toString());
key = (String) common.get(r.nextInt(common.size()));
return key;
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)