java和json的兄弟情义

1.首先引入依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.51</version>
</dependency>

2.编写java对象实体类

public class prove {
  
    private Integer prove_id;

    private String prove_url;
    private String prove_description;
    private Integer activity_id;
    private String topic;
}

3.实现java对象与Json字符串之间的转化

@Test
    void testProveAdd(){

        System.out.println(111);
        Object obj = JSONArray.toJSON("{
  "activity_id": 0,
  "prove_description": "string",
  "prove_id": 0,
  "prove_url": "string",
  "topic": "string"
}");

        String json = obj.toString();
        //使用FastJson从json串中根据key获取value :https://www.cnblogs.com/jun1019/p/7574800.html
        JSONObject jsonObject = JSONObject.parseObject(json);
        String prove_url=jsonObject.getString("prove_url");
        String prove_description=jsonObject.getString("prove_description");
        Integer activity_id=Integer.parseInt(jsonObject.getString("activity_id"));
        String topic=jsonObject.getString("topic");
        String new_prove_url = Base64Test.GenerateImagebendi(prove_url);
        prove newprove=new prove();
        newprove.setActivity_id(activity_id);
        newprove.setProve_description(prove_description);
        newprove.setProve_url(new_prove_url);
        newprove.setTopic(topic);
        tbScoreProveMapper.insertProve(newprove);
        System.out.println(newprove);
        TbScoreProve tbScoreProve1=tbScoreProveMapper.selectById(newprove.getProve_id());
        System.out.println(tbScoreProve1);

    }

4.获取json的某个key的值

JSONObject jsonObject = JSONObject.parseObject(json);
String prove_url=jsonObject.getString("prove_url");
String prove_description=jsonObject.getString("prove_description");
Integer activity_id=Integer.parseInt(jsonObject.getString("activity_id"));
String topic=jsonObject.getString("topic");

jackjson也是同样的道理具体可以自己查阅相关资料

参考资料

java对象与Json字符串之间的转化(fastjson)
使用FastJson从json串中根据key获取value

上一篇:Java 遍历json


下一篇:微信小程序用URL也能打开了