首页 文章

将JSON数据转换为Java对象

提问于
浏览
228

我希望能够在我的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对象的数组 . 目的是提取ID列表,其中任何给定对象拥有包含其他JSON对象的组属性 . 我把Google的Gson视为潜在的JSON插件 . 任何人都可以提供某种形式的指导,指导我如何从这个JSON字符串生成Java?

11 回答

  • 2

    我将Google的Gson视为潜在的JSON插件 . 任何人都可以提供某种形式的指导,指导我如何从这个JSON字符串生成Java?

    Google Gson支持泛型和嵌套bean . JSON中的 [] 表示一个数组,应该映射到Java集合(如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() .

    另见:

  • 304

    Gson的Bewaaaaare!它's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn'那很难) .

    此外,如果你有一个对象数组,并且你将一些json反序列化为该对象数组,那么真正的类型就是LOST!完整的对象甚至不会被复制!使用XStream ..如果使用jsondriver并设置正确的设置,将把丑陋的类型编码到实际的json中,这样你就不会丢失任何东西 . 真正的序列化要付出的小代价(丑陋的json) .

    请注意Jackson修复了这些问题,并且是faster而不是GSON .

  • 3

    奇怪的是,到目前为止提到的唯一合适的JSON处理器是GSON .

    这里有更好的选择:

    • JacksonGithub) - 强大的数据绑定(来自POJO的JSON),流(超快),树模型(便于无类型访问)

    • Flex-JSON - 高度可配置的序列化

    编辑(2013年8月):

    还需要考虑一下:

    • Genson - 与Jackson类似的功能,旨在让开发人员更容易配置
  • 25

    或者与 Jackson :

    String json = "...
    ObjectMapper m = new ObjectMapper();
    Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
    
  • 0

    如果通过任何更改,您在已经使用http://restfb.com/的应用程序中,那么您可以执行以下操作:

    import com.restfb.json.JsonObject;
    
    ...
    
    JsonObject json = new JsonObject(jsonString);
    json.get("title");
    

    等等

  • 0

    如果您使用任何类型的特殊 Map ,其中包含特殊 Map 的键或值,您会发现谷歌的实施并未考虑到这一点 .

  • 3
    HashMap keyArrayList = new HashMap();
            Iterator itr = yourJson.keys();
            while (itr.hasNext())
            {
                String key =(String) itr.next();
                keyArrayList.put(key, yourJson.get(key).toString());
            }
    
  • 14

    简单而有效的java代码将JSONObject转换为Java Object

    Employee.java

    import java.util.HashMap;
    import java.util.Map;
    
    import javax.annotation.Generated;
    
    import com.fasterxml.jackson.annotation.JsonAnyGetter;
    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @Generated("org.jsonschema2pojo")
    @JsonPropertyOrder({
    "id",
    "firstName",
    "lastName"
    })
    public class Employee {
    
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("firstName")
    private String firstName;
    @JsonProperty("lastName")
    private String lastName;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
    /**
    *
    * @return
    * The id
    */
    @JsonProperty("id")
    public Integer getId() {
    return id;
    }
    
    /**
    *
    * @param id
    * The id
    */
    @JsonProperty("id")
    public void setId(Integer id) {
    this.id = id;
    }
    
    /**
    *
    * @return
    * The firstName
    */
    @JsonProperty("firstName")
    public String getFirstName() {
    return firstName;
    }
    
    /**
    *
    * @param firstName
    * The firstName
    */
    @JsonProperty("firstName")
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }
    
    /**
    *
    * @return
    * The lastName
    */
    @JsonProperty("lastName")
    public String getLastName() {
    return lastName;
    }
    
    /**
    *
    * @param lastName
    * The lastName
    */
    @JsonProperty("lastName")
    public void setLastName(String lastName) {
    this.lastName = lastName;
    }
    
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
    }
    
    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
    }
    
    }
    

    LoadFromJSON.java

    import org.codehaus.jettison.json.JSONObject;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class LoadFromJSON {
    
        public static void main(String args[]) throws Exception {
            JSONObject json = new JSONObject();
            json.put("id", 2);
            json.put("firstName", "hello");
            json.put("lastName", "world");
    
            byte[] jsonData = json.toString().getBytes();
    
            ObjectMapper mapper = new ObjectMapper();
            Employee employee = mapper.readValue(jsonData, Employee.class);
    
            System.out.print(employee.getLastName());
    
        }
    }
    
  • 3

    标准的东西有什么问题?

    JSONObject jsonObject = new JSONObject(someJsonString);
    JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
    String value = jsonArray.optJSONObject(i).getString("someJsonValue");
    
  • 43

    尝试一下:

    https://github.com/RichardHightower/boon

    这是邪恶的:

    https://github.com/RichardHightower/json-parsers-benchmark

    不要相信我的话......看看gatling基准 .

    https://github.com/gatling/json-parsers-benchmark

    (在某些情况下,最多4倍,并且在100次测试中 . 它还具有更快的索引覆盖模式 . 它很年轻但已经有一些用户 . )

    它可以比任何其他lib解析为JSON DOM并且没有Index Overlay模式更快地将JSON解析为Maps和Lists . 使用Boon Index Overlay模式,它甚至更快 .

    它还具有非常快的JSON松弛模式和PLIST解析器模式 . :)(并且具有超低内存,直接从字节模式直接使用UTF-8编码) .

    它也具有最快的JSON到JavaBean模式 .

    这是新的,但如果您正在寻找速度和简单的API,我认为没有更快或更简约的API .

  • 6

    根据输入的JSON格式(字符串/文件)创建一个jSONString . 可以获得与JSON对应的示例Message类对象,如下所示:

    消息msgFromJSON = new ObjectMapper() . readValue(jSONString,Message.class);

相关问题