gson怎么把字符串转成json
1个回答
展开全部
示例:
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
public class DemoGson {
public static void main(String[] args) {
//初始化对象
Gson gson = new Gson();
Person jack = new Person("Jack", "Beijing");
Dog wangwang = new Dog("wangwang", "BLACK",2);
HashMap map = new HashMap();
map.put("person", jack);
map.put("dog", wangwang);
//将Person类转化成json
String jackJson = gson.toJson(jack);
System.out.println(jackJson);
//将json转化成Person类
Person person2 = gson.fromJson(jackJson, Person.class);
System.out.println("name:"+ person2.name);
System.out.println("city:"+ person2.city);
//将Map转化成json
String mapJson = gson.toJson(map);
System.out.println(mapJson);
//将json转化成Map
Map map2 = gson.fromJson(mapJson, Map.class);
System.out.println(map2);
}
}
class Person{
public String name;
public String city;
public Person(String name,String city){
this.name = name;
this.city = city;
}
}
class Dog{
public String name ;
public String color;
public int weight;
public Dog(String name,String color,int weight){
this.name = name;
this.color = color;
this.weight = weight;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询