将 JSON 数据转换为 Java 对象

发布于 2024-08-10 18:16:39 字数 639 浏览 9 评论 0原文

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

I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson(). Below is an example of what the string can look like:

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

In this string every JSON object contains an array of other JSON objects. The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

川水往事 2024-08-17 18:16:39

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

另请参阅:

I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

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

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

See also:

三月梨花 2024-08-17 18:16:39

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

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

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

Bewaaaaare of Gson! It'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't that hard).

Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Note that Jackson fixes these issues, and is faster than GSON.

千纸鹤 2024-08-17 18:16:39

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

这里有更多不错的选择:

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

编辑(2013 年 8 月):

还有一个需要考虑的:

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

Oddly, the only decent JSON processor mentioned so far has been GSON.

Here are more good choices:

  • Jackson (Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
  • Flex-JSON -- highly configurable serialization

EDIT (Aug/2013):

One more to consider:

  • Genson -- functionality similar to Jackson, aimed to be easier to configure by developer
痴情 2024-08-17 18:16:39

或者和杰克逊一起:

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

Or with Jackson:

String json = "...";
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
少年亿悲伤 2024-08-17 18:16:39

简单且有效的 Java 代码将 JSONObject 转换为 Java 对象

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

    }
}

Easy and working java code to convert JSONObject to 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());

    }
}
皇甫轩 2024-08-17 18:16:39

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

import com.restfb.json.JsonObject;

...

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

ETC。

If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

import com.restfb.json.JsonObject;

...

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

etc.

独﹏钓一江月 2024-08-17 18:16:39

根据输入 JSON 格式(字符串/文件)创建一个 jsonString。 JSON对应的Message类对象示例如下:

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

Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
阳光①夏 2024-08-17 18:16:39
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}
沉鱼一梦 2024-08-17 18:16:39

如果您使用任何类型的带有特殊映射键或值的特殊映射,您会发现谷歌的实现没有考虑到这一点。

If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.

空心↖ 2024-08-17 18:16:39

标准的东西有什么问题?

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

What's wrong with the standard stuff?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
笑红尘 2024-08-17 18:16:39

以这种方式传递 JSON 文件,它将返回对象。

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

Pass your JSON file in this way, it will return the object.

File file = new File("D:\\Coding\\tickets\\temp.json");
ObjectMapper om = new ObjectMapper();
Profile profile = om.readValue(file, new TypeReference<Profile>() {});
安静被遗忘 2024-08-17 18:16:39

尝试一下 boon:

https://github.com/RichardHightower/boon

速度非常快:

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

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

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

(最多 4 倍)在某些情况下,经过数百次测试,它还有一个更快的索引覆盖模式。它还很年轻,但已经有了一些用户。)

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

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

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

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

Give boon a try:

https://github.com/RichardHightower/boon

It is wicked fast:

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

Don't take my word for it... check out the gatling benchmark.

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

(Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)

It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.

It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).

It also has the fastest JSON to JavaBean mode too.

It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.

清风夜微凉 2024-08-17 18:16:39

最简单的方法是您可以使用此 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);
}

The easiest way is that you can use this softconvertvalue method which is a custom method in which you can convert jsonData into your specific Dto class.

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);
}
一笔一画续写前缘 2024-08-17 18:16:39

        <!-- GSON -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.7</version>
        </dependency>
  @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;
    }

        <!-- GSON -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.7</version>
        </dependency>
  @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;
    }
極樂鬼 2024-08-17 18:16:39

使用雅加达 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")

Using the Jakarta JSON-P standard,

<!-- 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")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文