我希望能够从 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?

有帮助吗?

解决方案

我看着在谷歌的+个人资料相关联作为一个潜在的JSON插件。任何人都可以提供某种形式的指导如何我可以产生Java从这JSON串?

谷歌+个人资料相关联 支持泛型和嵌套豆。的 [] 关系图来描述软件所需的依赖代表阵列,并应线图Java收集诸如 List 或者只是一个普通的Java阵列。的 {} 关系图来描述软件所需的依赖表示一个目的,并应线图Java Map 或者只是一些JavaBean类。

你有一个JSON目与几个性的 groups 酒店表示一系列的嵌套对象的非常相同的类型。这可以分析与新评价将公开与以下方式:

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 的 Bewaaaaare!这非常酷,非常棒,但是当您想做除简单对象之外的任何事情时,您可能很容易需要开始构建自己的序列化器(这不是 难的)。

另外,如果您有一个对象数组,并且将一些 json 反序列化到该对象数组中,则真正的类型将丢失!完整的对象甚至不会被复制!使用XStream..如果使用 jsondriver 并设置正确的设置,会将丑陋的类型编码到实际的 json 中,这样您就不会丢失任何内容。真正的序列化要付出很小的代价(丑陋的 json)。

注意 杰克逊 解决了这些问题,并且是 快点 比GSON。

奇怪的是,只有体面的JSON处理器提到迄今为止已经+个人资料相关联.

这里有更好的选择:

  • 杰克逊 ()--强大的数据结合(计/从独的),流(超速),树模型(便于无类型的访问)
  • Flex-JSON --高度化配置

编辑(Aug/2013年):

一个更加以考虑:

  • Genson -功能类似于杰克逊,目的是更加容易配置的开发

或者与杰克逊:

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");

如果您使用任何类型的特殊地图的键或值也是特殊的地图,你会发现它不是由谷歌的执行预期的。

易和工作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());

    }
}
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");

提供福音尝试:

https://github.com/RichardHightower/boon

有恶快:

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

不要把我的话......检查出加特林基准。

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

(高达4倍的某些情况下,进出测试的100S的,它也有一个指数叠加模式还要快,这是年轻,但已经有一些用户。)

它可以解析JSON到地图和解释比任何其他的lib更快可以解析到一个JSON DOM和即没有指数叠加模式。随着宝指数覆盖模式,甚至更快。

它也具有非常快的JSON松懈模式和PLIST解析器模式。 :)(并具有超低存储器,直接从字节模式与在飞行UTF-8编码)。

它还具有最快的JSON来的JavaBean模式太。

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

根据输入JSON格式(串/文件)创建一个jSONString。可以如下获得对应于JSON样品Message类对象:

信息msgFromJSON =新ObjectMapper()readValue(jSONString,Message.class);

最简单的方法是,你可以使用这个方法softconvertvalue这是您可以在其中jsonData转换成特定DTO类的定制方法。

Dto response = softConvertValue(jsonData, Dto.class);


public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
{
    ObjectMapper objMapper = new ObjectMapper();
    return objMapper
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .convertValue(fromValue, toValueType);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top