java对象与Json字符串之间的转化(fastjson)

1.首先引入json jar包

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

2.创建user类

package com.lc.node.cloud.model;

import java.io.Serializable;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.annotation.JsonFormat;

1.创建User类

public class User implements Serializable{

    private static final long serialVersionUID = 1L;
    
    private String password;
    
    private String username;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

 

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

public class UserTest {
   public static void main(String[] args) {
      // 实现java对象与Json字符串之间的转化
      // 2. User对象与json之间的转换
      //2.1 将User对象转成json
        User u = new User();
          u.setUserName("xiaoming");
          u.setPassWord("0000")
        JSONObject obj = JSONObject.fromObject(u);
        System.out.println("将User对象转成json:" + obj);
        
     //2.2 将json字符串转成User对象
        u =(User)JSONObject.toBean(obj,User.class);
        System.err.println(u.getUserName());     
  } 
}

3.java List<User>集合与json之间的转换

public class UserListTest {
   public static void main(String[] args) {
// 3. 将List<User>与json之间的转换
     //3.1 将List<User>转成json
        User user = new User ();
        user.setUserName("00001");
        User user2 = new User ();
        user2.setUserName("00002");
        List<User> datas = new ArrayList<User>();
        datas.add(user );
        datas.add(user2 );
        JSONArray jArray = JSONArray.fromObject(datas);
        System.err.println(jArray.get(0));
     // 3.3. 将json字符串转成List<User>对象
        datas = JSONArray.toList(jArray, User.class);
        System.err.println(datas.get(0).getUserId());
  } 
}

4..java Map<Object,Object>集合与json之间的转换

public class UserListTest {
   public static void main(String[] args) {
       // 4. 将Map对象与json之间的转换
        // 4.1 将Map转成json
        User user = new User ();
        user.setUserName("00001");
        User user2 = new User ();
        user2.setUserName("00002");
        Map<Object, Object> map = new HashMap<Object,Object>();
        map.put("user1", dataTemplate);
        map.put("user2", dataTemplates);
        JSONObject  myJson = JSONObject.fromObject(map);
        System.err.println(myJson.toString());
      // 4.2.将json字符串转成map
        Map<Object, Object> map2 = myJson;
        dataTemplates = (DeleteData) map.get("user2");
        System.err.println(dataTemplates.getUserId());
        System.err.println(jArray.get(0));
   
  } 
}

 

上一篇:SQLSever语句(增、删、改、查)一、增:有4种方法1.使用insert插入单行数据


下一篇:Gson与FastJson详解