您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
三六零分类信息网 > 鹤岗分类信息网,免费分类信息发布

如何在Java中将JSON解析为Gson树模型?

2025/9/3 9:19:28发布42次查看
gson 库可用于将 json 字符串解析为树模型。我们可以使用 jsonparser 将 json 字符串解析为 jsonelement 类型的树模型。 jsonelement  的 getasjsonobject() 方法可用于获取 jsonobject  和 getasjsonarray( ) jsonelement方法可用于获取 jsonarray 形式的元素。
语法public jsonobject getasjsonobject()public jsonarray getasjsonarray()
示例import java.util.list;import com.google.gson.*;public class jsontreemodeltest { public static void main(string args[]){ string jsonstr = "{\"name\":\"adithya\",\"age\":20,\"year of passout\":2005,\"subjects\": [\"mathematics\",\"physics\",\"chemistry\"]}"; jsonparser jsonparser = new jsonparser(); jsonelement jsonelement = jsonparser.parse(jsonstr); if(jsonelement.isjsonobject()) { jsonobject studentobj = jsonelement.getasjsonobject(); system.out.println("student info:"); system.out.println("name is: " + studentobj.get("name")); system.out.println("age is: " + studentobj.get("age")); system.out.println("year of passout: " + studentobj.get("year of passout")); jsonarray jsonarray = studentobj.getasjsonarray("subjects"); system.out.println("subjects:" + jsonarray); } }}// student classclass student { private string name; private int age; private int passoutyear; private list subjects; public student(string name, int age, int passoutyear, list subjects) { this.name = name; this.age = age; this.passoutyear = passoutyear; this.subjects = subjects; } @override public string tostring() { return "student{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", year of passout=" + passoutyear + ", subjects=" + subjects + '}'; }}
输出student info:name is: "adithya"age is: 20year of passout: 2005subjects:["mathematics","physics","chemistry"]
以上就是如何在java中将json解析为gson树模型?的详细内容。
鹤岗分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product