将 JSON 数据转换为 Java 对象

问题描述 投票:0回答:15

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

java json jackson gson
15个回答
368
投票

我将 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()
.

另请参阅:


51
投票

Gson 的 Bewaaaaare!这非常酷,非常棒,但是当您想做除简单对象之外的任何事情时,您可能很容易需要开始构建自己的序列化器(这并不难)。 此外,如果您有一个对象数组,并且将一些 json 反序列化到该对象数组中,则真正的类型将丢失!完整的对象甚至不会被复制!使用 XStream.. 如果使用 jsondriver 并设置正确的设置,会将丑陋的类型编码到实际的 json 中,这样你就不会丢失任何东西。真正的序列化要付出很小的代价(丑陋的 json)。

请注意,

Jackson

修复了这些问题,并且比 GSON 更快


28
投票

这里还有更多不错的选择:

    Jackson
  • (Github) -- 强大的数据绑定(JSON 到/来自 POJO)、流式传输(超快)、树模型(方便非类型化访问)
  • Flex-JSON
  • ——高度可配置的序列化
  • 编辑(2013 年 8 月):

还有一个需要考虑的:

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

24
投票

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



10
投票
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()); } }



8
投票
http://restfb.com/

那么您可以执行以下操作: import com.restfb.json.JsonObject; ... JsonObject json = new JsonObject(jsonString); json.get("title");

等等


6
投票

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



5
投票


3
投票


2
投票

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



1
投票

File file = new File("D:\\Coding\\tickets\\temp.json"); ObjectMapper om = new ObjectMapper(); Profile profile = om.readValue(file, new TypeReference<Profile>() {});



0
投票

https://github.com/RichardHightower/boon

速度太快了:

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

不要相信我的话...查看加特林基准测试。

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

(在某些情况下高达 4 倍,并且经过了 100 次测试。它还有更快的索引覆盖模式。它还很年轻,但已经有一些用户了。)

它将 JSON 解析为地图和列表的速度比任何其他库解析为 JSON DOM 的速度都要快,并且没有索引覆盖模式。使用 Boon Index Overlay 模式,速度甚至更快。

它还有一个非常快的 JSON lax 模式和一个 PLIST 解析器模式。 :)(并且内存超低,直接从字节模式使用 UTF-8 即时编码)。

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

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


0
投票

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



0
投票
  @Test
    void readListJsonFromFileTest() throws IOException {

        Type type = new TypeToken<List<SimplePojo>>(){}.getType();

        String fromJsonFile = readFromJsonFile("json/simplePojoJsonList.json");

        List<SimplePojo> pojoList = gson.fromJson(fromJsonFile, type);

        Assertions.assertNotNull(pojoList);
    }

    @Test
    void readJsonFromFileTest() throws IOException {

        Type type = new TypeToken<SimplePojo>(){}.getType();

        String fromJsonFile = readFromJsonFile("json/simplePojoJson.json");

        SimplePojo simplePojo = gson.fromJson(fromJsonFile, type);

        Assertions.assertNotNull(simplePojo);
    }

     String readFromJsonFile(String pathToJson) throws IOException {

        InputStream resource = new ClassPathResource(pathToJson).getInputStream();

        String json = StreamUtils.copyToString(resource, StandardCharsets.UTF_8);

        return json;
    }


0
投票
JSON-P

标准 <!-- https://mvnrepository.com/artifact/jakarta.json/jakarta.json-api --> <dependency> <groupId>jakarta.json</groupId> <artifactId>jakarta.json-api</artifactId> <version>2.1.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.glassfish/jakarta.json --> <dependency> <groupId>org.glassfish</groupId> <artifactId>jakarta.json</artifactId> <version>2.0.1</version> </dependency>

JsonReader reader = Json.createReader(new StringReader(myJsonString));
JsonObject mainObject = reader.readObject();
JsonArray groups = mainObject.getJsonArray(groups);
JsonObject firstGroup = mainObject.getJsonObject(0);
int firstId = firstGroup.getInt("id")
© www.soinside.com 2019 - 2024. All rights reserved.