将深层嵌套的 json 转换为 java 对象,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30174970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:35:56  来源:igfitidea点击:

Converting deeply nested json to java object and vice versa

javajson

提问by HymanSparrow

I am using JAXB for my json conversion to java object. The problem I am facing is that it leads me to create huge number of classes which serves no purpose except acting as a place holder for json tags.

我正在使用 JAXB 将 json 转换为 java 对象。我面临的问题是它导致我创建了大量的类,这些类除了充当 json 标签的占位符之外没有任何用处。

For example: Consider below json:

例如:考虑下面的json:

{
"proposalAggregation": {
    "Buys": {
        "Heading1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        },
        "Heading2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
    },
    "Sells": {
        "Heading1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        },
        "Heading2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
    },
    "TAChanges": {
        "Heading1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        },
        "Heading2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
    },
    "Existing": {
        "Heading1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        },
        "Heading2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
    },
    "Proposed": {
        "Heading1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        },
        "Heading2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
    },
    "PIAChanges": {
        "Heading1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        },
        "Heading2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
    }
}

}

}

Now to deserialize this JSON as-is to java object these are the java classes i need to create:

现在要将这个 JSON 按原样反序列化为 java 对象,这些是我需要创建的 java 类:

Class ProposalAggregation --> this contains Buys, sells, existing, porposed,TAChanges, PIA

Class Buys extends Calculation
Class Sells extends Calculation
Class Existing extends Calculation
Class proposed extends Calculation
Class TAChanges extends Calculation
Class PIAChanges extends Calculation 
Class Calculation -- > this contains heading1 and heading2

class Heading1
Class Heading2

So in total 9 classes to mimic above JSON and if we looks at the role of these classes they are nothing but place holders for JSON tags. Is there any easy way for this ?

所以总共有 9 个类来模仿 JSON,如果我们看看这些类的作用,它们只不过是 JSON 标签的占位符。有什么简单的方法吗?

回答by Pramod Karandikar

You can implement Google's GSON library in following manner. Have shown with a sample class, you can modify it further.

您可以通过以下方式实现 Google 的 GSON 库。已经展示了一个示例类,您可以进一步修改它。

Class - ProposalAggregation

类 - ProposalAggregation

package com.test;

import java.util.Map;

public class ProposalAggregation {

private Map<String, Map<String, String>> Buys;
private Map<String, Map<String, String>> Sells;
private Map<String, Map<String, String>> TAChanges;

public Map<String, Map<String, String>> getBuys() {
    return Buys;
}

public void setBuys(Map<String, Map<String, String>> buys) {
    Buys = buys;
}

public Map<String, Map<String, String>> getSells() {
    return Sells;
}

public void setSells(Map<String, Map<String, String>> sells) {
    Sells = sells;
}

public Map<String, Map<String, String>> getTAChanges() {
    return TAChanges;
}

public void setTAChanges(Map<String, Map<String, String>> tAChanges) {
    TAChanges = tAChanges;
}

public String toString() {
    return "BUYS=" + this.Buys + " \nSELLS=" + this.Sells + " \nTACHANGES="
            + this.TAChanges;
}

}

}

Test main classNote that I have modified keynames just to verify the conversion is correct.

测试主类请注意,我修改了key名称只是为了验证转换是否正确。

package com.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

public class TestClass {

    public static void main(String[] args) {
        Gson gson = new Gson();

        try {

            String jsonString = " { 'Buys': { 'bHeading1': { 'bkey1': 'value1', 'bkey2': 'value2', 'bkey3': 'value3' }, 'bbHeading2': { 'bbkey1': 'value1', 'bbkey2': 'value2', 'bbkey3': 'value3' } }, "
                    + "'Sells': { 'sHeading1': { 'skey1': 'value1', 'skey2': 'value2', 'skey3': 'value3' }, 'ssHeading2': { 'sskey1': 'value1', 'sskey2': 'value2', 'sskey3': 'value3' } }, "
                    + "'TAChanges': { 'Heading1': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }, 'Heading2': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } }, 'Existing': { 'Heading1': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }, 'Heading2': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } }, 'Proposed': { 'Heading1': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }, 'Heading2': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } }, 'PIAChanges': { 'Heading1': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }, 'Heading2': { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } } }";


            // convert to java class
            ProposalAggregation obj = gson.fromJson(jsonString, ProposalAggregation.class);
            System.out.println("OBJECT : " + obj);

            // convert to json
            String jsonStringFromObj = gson.toJson(obj);
            System.out.println("JSON : " + jsonStringFromObj);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Here's the output.

这是输出。

OBJECT : BUYS={bHeading1={bkey1=value1, bkey2=value2, bkey3=value3}, bbHeading2={bbkey1=value1, bbkey2=value2, bbkey3=value3}} 
SELLS={sHeading1={skey1=value1, skey2=value2, skey3=value3}, ssHeading2={sskey1=value1, sskey2=value2, sskey3=value3}} 
TACHANGES={Heading1={key1=value1, key2=value2, key3=value3}, Heading2={key1=value1, key2=value2, key3=value3}}
JSON : {"Buys":{"bHeading1":{"bkey1":"value1","bkey2":"value2","bkey3":"value3"},"bbHeading2":{"bbkey1":"value1","bbkey2":"value2","bbkey3":"value3"}},"Sells":{"sHeading1":{"skey1":"value1","skey2":"value2","skey3":"value3"},"ssHeading2":{"sskey1":"value1","sskey2":"value2","sskey3":"value3"}},"TAChanges":{"Heading1":{"key1":"value1","key2":"value2","key3":"value3"},"Heading2":{"key1":"value1","key2":"value2","key3":"value3"}}}

回答by abhishrp

Use Hymanson instead of JAXB. Refer the following link for more details. http://wiki.fasterxml.com/HymansonInFiveMinutes

使用 Hymanson 而不是 JAXB。有关详细信息,请参阅以下链接。 http://wiki.fasterxml.com/HymansonInFiveMinutes

回答by coolest_head

It is not clear from OP but if you do not even need classes, Hymanson can deserialize JSON into HashMap of HashMaps and do the reverse as well. link to a blog doing the same

从 OP 中不清楚,但如果您甚至不需要类,Hymanson 可以将 JSON 反序列化为 HashMaps 的 HashMap 并执行相反的操作。 链接到一个做同样事情的博客