更多请读:http://blog.csdn.net/lk_blog/article/details/7685169
package JSON;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class TestJSON {
public class User {
private String username;
private int userId;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
/**
* @param args
*/
public static void main(String[] args) {
Gson gson = new Gson();
Map map = new HashMap();
map.put("a", "b");
map.put("c", 5);
System.out.println(gson.toJson(map));
String jsonData = "{\"username\":\"arthinking\",\"userId\":123}";
User user = new Gson().fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
}
.
/**版本必须是:gson-2.2.4.jar及以上版本**/
public static void testMapString() {
GsonBuilder gb = new GsonBuilder();
Gson gson = gb.create();
Map map = new HashMap();
map.put("a" , "A");
map.put("b" , 999);
map.put("7" , 999);
String json = gson.toJson(map);
System.out.println(json);
Map map2 = gson.fromJson(json , HashMap.class);
for(Object each : map2.entrySet()) {
System.out.println(each);
}
}