我希望能够在Java操作方法中访问JSON字符串中的属性。该字符串可以通过简单地说myJsonString = object.getJson()来获得。以下是字符串外观的示例:
{
'title': 'ComputingandInformationsystems',
'id': 1,
'children': 'true',
'groups': [{
'title': 'LeveloneCIS',
'id': 2,
'children': 'true',
'groups': [{
'title': 'IntroToComputingandInternet',
'id': 3,
'children': 'false',
'groups': []
}]
}]
}在这个字符串中,每个JSON对象都包含一个由其他JSON对象组成的数组。其目的是提取一个is列表,其中任何具有包含其他JSON对象的组属性的给定对象。我把Google的Gson看作是一个潜在的JSON插件。关于如何从这个JSON字符串生成Java,谁能提供某种形式的指导?
发布于 2009-11-06 23:06:09
我把Google的Gson看作是一个潜在的
插件。关于如何从这个JSON字符串生成Java,谁能提供某种形式的指导?
Google Gson支持泛型和嵌套bean。JSON中的[]表示一个数组,应该映射到List之类的集合,或者只映射到普通的Java数组。JSON中的{}表示一个对象,应该映射到一个Java Map或某个JavaBean类。
您有一个具有多个属性的JSON对象,其中的groups属性表示完全相同类型的嵌套对象的数组。这可以通过以下方式使用Gson进行解析:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}很简单,不是吗?只要有一个合适的JavaBean并调用Gson#fromJson()即可。
另请参阅:
简介
发布于 2010-10-10 10:49:40
太棒了!它非常酷,非常棒,但当你想做简单对象以外的任何事情时,你可能很容易就需要开始构建你自己的序列化程序(这并不难)。
此外,如果您有一个对象数组,并且您将一些json反序列化为该对象数组,则真正的类型将丢失!完整的对象甚至不会被复制!使用XStream..如果使用jsondriver并设置了适当的设置,它会将丑陋的类型编码到实际的json中,这样您就不会丢失任何东西。为真正的序列化付出的小代价(丑陋的json)。
请注意,Jackson解决了这些问题,并且比GSON更简单。
https://stackoverflow.com/questions/1688099
复制相似问题