将JSON转换为Java

我想能够从我的Java操作方法中的JSONstring访问属性。 该string可以通过简单地说myJsonString = object.getJson() 。 下面是这个string的例子:

 { 'title': 'ComputingandInformationsystems', 'id': 1, 'children': 'true', 'groups': [{ 'title': 'LeveloneCIS', 'id': 2, 'children': 'true', 'groups': [{ 'title': 'IntroToComputingandInternet', 'id': 3, 'children': 'false', 'groups': [] }] }] } 

在这个string中,每个JSON对象都包含其他JSON对象的数组。 目的是提取任何给定对象拥有包含其他JSON对象的组属性的ID列表。 我把Google的Gson视为一个潜在的JSON插件。 任何人都可以提供某种forms的指导,如何从这个JSONstring中生成Java?

我把Google的Gson视为一个潜在的JSON插件。 任何人都可以提供某种forms的指导,如何从这个JSONstring中生成Java?

谷歌Gson支持generics和嵌套的豆。 JSON中的[]代表一个数组,并且应该映射到一个Java集合,比如List或者一个普通的Java数组。 JSON中的{}表示一个对象,应该映射到Java Map或者一些JavaBean类。

您有一个JSON对象,其中有几个属性,其中groups属性表示相同types的嵌套对象的数组。 这可以用Gson按以下方式parsing:

 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()调用Gson#fromJson()

也可以看看:

  • Json.org – JSON简介
  • Gson用户指南 – Gson简介

Gson的Bewaaaaare! 这非常酷,非常棒,但是除了简单对象以外,你可以轻松地开始构build自己的序列化器(这并不困难)。

另外,如果你有一个对象数组,并且你将一些json反序列化到这个对象数组中,那么真正的types是LOST! 完整的对象将不会被复制! 使用XStream ..其中,如果使用jsondriver并设置适当的设置,将丑陋的types编码到实际的json中,这样你就不会丢失任何东西。 一个小的代价(丑陋的JSON)真正的序列化。

请注意, Jackson修复了这些问题,比GSON 更快 。

奇怪的是,到目前为止提到的唯一像样的JSON处理器就是GSON。

这里有更好的select:

  • jackson ( Github ) – 强大的数据绑定(POJO的JSON),stream(超快速),树模型(便于无types访问)
  • Flex-JSON – 高度可configuration的序列化

编辑(2013年8月):

再考虑一下:

  • 简森 – 与jackson相似的function,旨在使开发人员更容易configuration

或与jackson:

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

如果通过任何更改,您所在的应用程序已经使用http://restfb.com/,那么您可以这样做:;

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

等等

如果您使用任何types的特殊地图,其中包含特殊地图的键或值,您将会发现它并不适用于谷歌的实施。

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

标准的东西有什么问题?

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

简单易用的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()); } } 

试试看:

https://github.com/RichardHightower/boon

它是邪恶的快速:

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

不要听我的话…检查加特基准。

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

(有些情况下,最高可达4倍,而100%的testing也是这样,还有一个更快的索引重叠模式,它很年轻,但已经有一些用户了。

它可以parsingJSON到地图和列表比任何其他库可以parsing到一个JSON DOM,并没有索引重叠模式。 使用Boon Index Overlay模式,速度更快。

它也有一个非常快的JSON宽松模式和一个PLISTparsing器模式。 :)(并有一个超低内存,直接从UTF-8编码的字节模式)。

它也是JavaBean模式中最快的JSON。

这是新的,但如果速度和简单的API是你在找什么,我不认为有一个更快或更简约的API。

根据input的JSON格式(string/文件)创build一个jSONString。 与JSON对应的消息类对象示例如下:

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