简体   繁体   中英

Convert a JSON object to another JSON object in Java

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. 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).

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.

EDIT: Sorry for the misunderstanding.

You should really go for a framework such as the one or @Alessio recommended. 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 . 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 .

You can use JsonPath to avoid the low-level JSONObject API calls.

Add the maven dependency:

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

Parse your JSON from String/File/URL/InputStream:

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.

The API also allows mapping and renaming elements in the DocumentContext.

See more:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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