从JSON反序列化复杂的嵌套Java对象 [英] Deserializing complex nested java objects from JSON

查看:884
本文介绍了从JSON反序列化复杂的嵌套Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个Java类Workspace,其中的字段具有产品列表类型的字段,其中包含模块列表类型的字段,其中包含具有对象类型的列表类型的字段.

So I have a java class Workspace that has field of type List of Product which contains field of type List of Module which contains field of type List with Objects.

所以我喜欢3个带有列表的嵌套对象.在JSON序列化和反序列化方面,最无痛的处理方式是什么?

So I have like 3 levels nested objects with lists. What is the most painless way to deal with this in regards to JSON serialization and deserialization?

目前,我正在使用GSON进行序列化,并且工作正常,但似乎没有优雅的方法来进行反序列化.

Currentlly I'm doing serialization with GSON and that works fine but it seems there is no elegant way to do deserialization.

我阅读了有关该主题的所有答案,但没有找到能解决我问题的任何东西.

I read all the answers on SO about this topics but have not found anything that solves my question.

这是问题

class Workspace{
List<Product> products;
}

class Product{
List<Module> modules;
}

class Module{
List<Parameter> parameters;
}

class Parameter{
String name;
String type;
}

有没有办法用几行代码进行反序列化?

Is there a way to do deserialization with few lines of code?

推荐答案

如果值得进行更改,并且愿意的话,我建议您看看Jackson(

If it's worth the change and if you are willing to I suggest you have a look to Jackson (https://github.com/FasterXML/jackson). It might do the trick out-of-the-box with few or no annotations or customization.

"Jackson是几种处理JSON的可用库之一.其他一些是Boon,GSON和Java API(用于JSON处理). Jackson相对于其他图书馆的优势之一是它的成熟度. Jackson已经发展到足以成为某些主要Web服务框架(...)首选的JSON处理库(...)"

"Jackson is one of the several available libraries for processing JSON. Some others are Boon, GSON, and Java API for JSON Processing. One advantage that Jackson has over other libraries is its maturity. Jackson has evolved enough to become the preferred JSON processing library of some major web services frameworks (...)"

关于DZone的这篇好文章可能会给您带来一些亮点: https://dzone. com/articles/processing-json-with-jackson

This good article of DZone may give you some highlights: https://dzone.com/articles/processing-json-with-jackson

尽管如此,由于您没有定义优雅"对您的含义,并且您在谈论GSON时,我同意这个答案可能不适合您(并且可能会消失;).

Nonetheless since you didn't define what "elegant" means to you and as you are speaking about GSON I agree this answer may not suit you (and might disappear ;)).

我阅读了有关该主题的所有答案,但没有找到能解决我问题的任何东西

I read all the answers on SO about this topics but have not found anything that solves my question

是的,如果您需要更多,还需要向我们提供有关您实际issue的详细信息.

And yep if you need more you will also need to provide us with details about your actual issue.

编辑:向杰克逊添加了示例代码. 这就是杰克逊看起来的优雅(当然,通过工厂,建造者,帮助者等预先配置的映射器,它甚至会更好).

EDIT: added sample code with Jackson. Here's how elegant it could look with Jackson (and of course it can even be better with pre-configured mappers through factories, builders, helpers...).

public class Workspace {
    final ObjectMapper objMapper = new ObjectMapper();
    List<Product> products;

    public Workspace() {
    }

    public Workspace(List<Product> products) {
        this.products = products;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public String serialize() throws IOException {
        try {
            return objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Workspace deserialize(String json) throws IOException {
        return new ObjectMapper().readValue(json, Workspace.class);
    }        
}

public class Product {
    List<Module> modules;

    public Product() {
    }

    public Product(List<Module> modules) {
        this.modules = modules;
    }

    public List<Module> getModules() {
        return modules;
    }

    public void setModules(List<Module> modules) {
        this.modules = modules;
    }
}


public class Module {
    List<Parameter> parameters;

    public Module() {
    }

    public Module(List<Parameter> parameters) {
        this.parameters = parameters;
    }

    public List<Parameter> getParameters() {
        return parameters;
    }

    public void setParameters(List<Parameter> parameters) {
        this.parameters = parameters;
    }      
}

public class Parameter {
    String name;
    String type;

    public Parameter() {
    }

    public Parameter(String name, String type) {
        this.name = name;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }      
}

public class WorkspaceTest {        
    /**
     * Test of serialize method, of class Workspace.
     */
    @Test
    public void testSerDeserialize() throws Exception {
        // Build sample:
        Workspace instance = new Workspace(
                Collections.singletonList(new Product(
                        Collections.singletonList(new Module(
                            Collections.singletonList(new Parameter("Hello","World")))))));

        // SER
        String serialized = instance.serialize();        
        assertNotNull(serialized);
        System.out.println("Serialized JSON: \n"+serialized);

        // DSER
        Workspace deserialized = Workspace.deserialize(serialized);            

        // MATCH
        assertEquals(serialized, deserialized.serialize());
        System.out.println("Match!");
    }
}

输出:

Serialized JSON: 
{
  "products" : [ {
    "modules" : [ {
      "parameters" : [ {
        "name" : "Hello",
        "type" : "World"
      } ]
    } ]
  } ]
}
Match!

这篇关于从JSON反序列化复杂的嵌套Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆