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;
}
标签:java,String,UserVO,对象,private,json,println
From: https://blog.csdn.net/m0_70630103/article/details/140271331