对象 JSON Map List Object JSONObject JSONArray 互相转换

对象 JSON Map List Object JSONObject JSONArray 互相转换

  • 创建个实体类
  • maven
  • JSON字符串 转 对象
  • JSON字符串 转 Map
  • JSON字符串 转 JSONObject
  • JSON字符串转List
  • 对象 转 JSON字符串
  • 对象 转 JSONObject
  • Map 转 JSON字符串
  • List 转 JSON字符串
  • LIst 转 JSONArray
  • JSONObject 转 JSON字符串
  • JSONArray转List

创建个实体类

 public class UmsPermission implements Serializable {    private Long id;    @ApiModelProperty(value = "父级权限id")    private Long pid;    @ApiModelProperty(value = "名称")    private String name;    @ApiModelProperty(value = "权限值")    private String value;    @ApiModelProperty(value = "图标")    private String icon;    @ApiModelProperty(value = "权限类型:0->目录;1->菜单;2->按钮(接口绑定权限)")    private Integer type;    @ApiModelProperty(value = "前端资源路径")    private String uri;    @ApiModelProperty(value = "启用状态;0->禁用;1->启用")    private Integer status;    @ApiModelProperty(value = "创建时间")    private Date createTime;    @ApiModelProperty(value = "排序")    private Integer sort;    private static final long serialVersionUID = 1L;    //省略所有getter及setter方法}

maven

jar 包, com.alibaba.fastjson 版本的jar包

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

JSON字符串 转 对象

// jsonStr json字符串// UmsPermission 实体类对象UmsPermission umsPermission  = JSON.parseObject(jsonStr, UmsPermission.class);

JSON字符串 转 Map

// jsonStr json字符串// UmsPermission 实体类对象Map<String,Object> map  = JSON.parseObject(jsonStr, Map.class);

JSON字符串 转 JSONObject

// jsonStr json字符串// UmsPermission 实体类对象JSONObject jsonObject = JSON.parseObject(jsonStr, JSONObject.class);

JSON字符串转List

//listJson 是ListJSON字符串 [{"id":"1","name":"张三"},{"id":"2","name":"李四"}]    List<UmsPermission> studentList = JSON.parseArray(listJson, UmsPermission.class);

对象 转 JSON字符串

UmsPermission umsPermission  = new UmsPermission();String jsonStr= JSONObject.toJSONString(umsPermission); // 返回jsonStr格式 {"id":"1","name":"张三"}

对象 转 JSONObject

 UmsPermission umsPermission = new UmsPermission(); //1、使用JSONObject        JSONObject json = JSONObject.fromObject(umsPermission);

Map 转 JSON字符串

Map Map = new HashMap<>();String jsonStr= JSONObject.toJSONString(Map);

List 转 JSON字符串

//list 对象List<UmsPermission> list = new ArrayList<UmsPermission>();String listJson = JSONObject.toJSONString(list);//list mapList<Map> list = new ArrayList<Map>();String listJson = JSONObject.toJSONString(list);

LIst 转 JSONArray

   List<UmsPermission> list = new ArrayList();    //2、使用JSONArray    JSONArray array = JSONArray.fromObject(list);

JSONObject 转 JSON字符串

 JSONObject jsonObject = new JSONObject(); String string = jsonObject.toJSONString();

JSONArray转List

JSONArray array = new JSONArray();List<Map<String,Object> list = JSONArray.toList(array, Map.class);

来源:https://www.icode9.com/content-4-909001.html

(0)

相关推荐