引入FastJson的jar
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
建Users实体类
package com.ccb.demossm.entity;
import org.springframework.stereotype.Component;
@Component
public class Users {
private String userId;
private String userName;
private String userPwd;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public Users(String userId, String userName, String userPwd) {
this.userId = userId;
this.userName = userName;
this.userPwd = userPwd;
}
public Users() {
}
}
JSON和java对象互相转化测试类
package com.ccb.demossm;
import com.alibaba.fastjson.JSONObject;
import com.ccb.demossm.entity.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestParam;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestFastJson {
@Test
public void test() {
String string = "{\"userId\":\"132234\",\"userName\":\"小明\",\"userPwd\":\"54s85f\"}";
Users users = JSONObject.parseObject(string,Users.class);
Users users1 = new Users();
users1.setUserId("12");
users1.setUserName("xiaohong");
users1.setUserPwd("58748");
String string1 = JSONObject.toJSONString(users1);
}
}