简体   繁体   English

在Java中将JSON对象转换为另一个JSON对象

[英]Convert a JSON object to another JSON object in Java

Java class JSONObject : Java class JSONObject

I have a JSON object, from which I want to extract only some of the key/value pairs into another JSON object. 我有一个JSON对象,我只想从其中提取一些键/值对到另一个JSON对象中。 In addition, I want to change the names of the extracted keys. 另外,我想更改提取键的名称。 And finally, I want to have the output object "flat" (ie, all the elements in depth 1). 最后,我要使输出对象“平坦”(即深度1中的所有元素)。

For example: 例如:

Input object: 输入对象:

{
    "a":"val_a",
    "b":
    {
        "b1":"val_b1",
        "b2":"val_b2"
    },
    "c":
    {
        "c1":"val_c1",
        "c2":
        {
            "c21":"val_c21",
            "c22":"val_c22"
        }
    }
}

Output object: 输出对象:

{
    "x":"val_a",
    "y":"val_b1",
    "z":"val_c22"
}

What is the best ("cleanest") way to implement this? 什么是实现此目的的最佳方式(“最干净的”)?

At present, I'm extracting the fields one by one "manually", like so (for the example above): 目前,我正在“手动”一个接一个地提取字段,例如(对于上面的示例):

JSONObject output = new JSONObject();
output.put("x",input.getString("a"));
output.put("y",input.getJSONObject("b").getString("b1"));
output.put("z",input.getJSONObject("c").getJSONObject("c2").getString("c22"));

Is there some sort of "regular expression" that would help me to achieve this in "one shot"? 是否有某种“正则表达式”可以帮助我“一次完成”?

An answer on the given example would be highly appreciated. 给定示例的答案将不胜感激。

Thanks 谢谢

One alternative could be to use the JSON in Java framework to transform your JSON object into Java, perform operations and generate new JSON objects. 一种替代方法是在Java框架中使用JSON将JSON对象转换为Java,执行操作并生成新的JSON对象。

EDIT: Sorry for the misunderstanding. 编辑:抱歉造成误会。

You should really go for a framework such as the one or @Alessio recommended. 您确实应该选择一个推荐的框架,例如@或@Alessio。 Although this should be possible to be done through the use of a regular expression, personally, I would recommend against it since a change in nesting and/or object you are looking for can bring about a big change in the regex itself. 尽管这应该可以通过使用正则表达式来完成,但就个人而言,我还是建议要这样做,因为您要查找的嵌套和/或对象的更改可能会导致正则表达式本身发生很大的更改。 Thus, although a regex can get the job done quicker, it might not be as readable and maintainable. 因此,尽管正则表达式可以更快地完成工作,但它可能不那么易读和可维护。

There are some frameworks, that might help you achieving what you are looking for. 有一些框架可以帮助您实现所需的目标。 The problem is that they are too complicated for simple jobs like this. 问题在于它们对于像这样的简单工作来说太复杂了。

You might have a look at Apache Camel , YQL , QL.IO , Teiid , Stardust . 您可以看看Apache CamelYQLQL.IOTeiidStardust All of them are frameworks for data virtualization/integration on different levels and can do the job. 它们都是用于不同级别的数据虚拟化/集成的框架,并且可以完成任务。 The question is if you really need such an infrastructure and how many data transformations do you really have? 问题是,您是否真的需要这样的基础架构?您真正拥有多少个数据转换?

If you have only this transformation, then I would recommend you to use GSON or Apache Camel . 如果只有这种转换,那么我建议您使用GSONApache Camel

You can use JsonPath to avoid the low-level JSONObject API calls. 您可以使用JsonPath避免低级JSONObject API调用。

Add the maven dependency: 添加Maven依赖项:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.2.0</version>
</dependency>

Parse your JSON from String/File/URL/InputStream: 从String / File / URL / InputStream解析您的JSON:

DocumentContext doc = JsonPath.parse(String|File|URL|InputStream data);

Then you will be able to use either the dot or key notation, whichever you prefer: 然后,您将可以使用点或键表示法,无论哪种方式:

String title = doc.read("$.store.book[0].title");

or 要么

String title = doc.read("$['store']['book'][0]['title']");

Similar to // in XPath you can use .. to get children nodes anywhere in the tree. 类似于XPath中的// ,您可以使用..获取树中任何位置的子节点。

The API also allows mapping and renaming elements in the DocumentContext. 该API还允许在DocumentContext中映射和重命名元素。

See more: 查看更多:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM