Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JSON数据转换为Java对象_Java_Json_Jackson_Gson - Fatal编程技术网

将JSON数据转换为Java对象

将JSON数据转换为Java对象,java,json,jackson,gson,Java,Json,Jackson,Gson,我希望能够从Java操作方法中的JSON字符串访问属性。只需说出myJsonString=object.getJson()即可获得该字符串。下面是字符串的示例: { 'title': 'ComputingandInformationsystems', 'id': 1, 'children': 'true', 'groups': [{ 'title': 'LeveloneCIS', 'id': 2, 'children

我希望能够从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对象的group属性。我把谷歌的Gson看作是一个潜在的JSON插件。有人能提供一些形式的指导,告诉我如何从这个JSON字符串生成Java吗

我把谷歌的Gson看作是一个潜在的JSON插件。有人能提供一些形式的指导,告诉我如何从这个JSON字符串生成Java吗

支持泛型和嵌套bean。JSON中的
[]
表示一个数组,应该映射到一个Java集合,比如或只是一个普通Java数组。JSON中的
{}
表示一个对象,应该映射到Java或某个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);
    }
}
package com.stackoverflow.q1688099;
导入java.util.List;
导入com.google.gson.gson;
公开课考试{
公共静态void main(字符串…参数)引发异常{
字符串json=
"{"
+“‘标题’:‘计算与信息系统’,”
+“'id':1,”
+“‘儿童’:‘正确’,”
+“‘组’:[{”
+“‘标题’:‘一级CI’,”
+“'id':2,”
+“‘儿童’:‘正确’,”
+“‘组’:[{”
+“‘标题’:‘计算与互联网简介’,”
+“'id':3,”
+“'children':'false'”
+“‘组’:[]”
+ "}]" 
+ "}]"
+ "}";
//现在做魔术。
Data Data=new Gson().fromJson(json,Data.class);
//展示它。
系统输出打印项次(数据);
}
}
类数据{
私有字符串标题;
私人长id;
私生子;
私人名单组;
公共字符串getTitle(){return title;}
public Long getId(){return id;}
公共布尔getChildren(){return children;}
public List getGroups(){return groups;}
public void setTitle(字符串标题){this.title=title;}
public void setId(长id){this.id=id;}
public void setChildren(布尔子项){this.children=children;}
public void setGroups(列表组){this.groups=groups;}
公共字符串toString(){
返回字符串.格式(“标题:%s,id:%d,子项:%s,组:%s”,标题,id,子项,组);
}
}
相当简单,不是吗?只要有一个合适的JavaBean和调用

另见:
  • -JSON简介
  • -Gson简介

如果您使用任何类型的特殊地图,其中也包含特殊地图的键或值,您会发现google的实现并未考虑到这一点。

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

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


请注意,它修复了这些问题,并且比GSON更有效。

奇怪的是,迄今为止提到的唯一一个像样的JSON处理器是GSON

以下是更好的选择:

  • ()--强大的数据绑定(与POJO之间的JSON)、流式传输(超快)、树模型(便于非类型化访问)
  • --高度可配置的序列化
编辑(2013年8月):

还有一点需要考虑:

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

如果通过任何更改,您所在的应用程序已在使用,则您可以执行以下操作:

import com.restfb.json.JsonObject;

...

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

或与杰克逊一起:

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

标准材料有什么问题

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

它的速度非常快:

不要相信我的话。。。查看gatling基准测试

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

它将JSON解析为映射和列表的速度比任何其他库解析为JSON DOM的速度都快,而且没有索引覆盖模式。使用Boon索引覆盖模式,速度更快

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

它还有最快的JSON到JavaBean模式


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

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

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
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);
}

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

    }
}

最简单的方法是可以使用这个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);
}
Dto response=softConvertValue(jsonData,Dto.class);
公共静态T-sof
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);
}