User.java
package com.stujs.po;
public class User {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
StuGSON.java
package com.stujs.gson;
import org.junit.Test;
import com.google.gson.Gson;
import com.stujs.po.User;
public class StuGSON {
@Test
public void test2JSON(){
User user = new User();
user.setName("ganett");
user.setAddress("NBA");
Gson gson = new Gson();
String userJson = gson.toJson(user);
System.out.println(userJson);
}
@Test
public void test2Object(){
String userJson = "{'name':'hchzh','address':'China'}";
Gson gson = new Gson();
User user = gson.fromJson(userJson, User.class);
System.out.println("Name-----"+user.getName());
System.out.println("Address-----"+user.getAddress());
}
}