在Java中将JSON对象转换为另一个JSON对象
Java class JSONObject
:
Java class JSONObject
:
我有一个JSON对象,我只想从其中提取一些键/值对到另一个JSON对象中.另外,我想更改提取键的名称.最后,我要使输出对象平坦"(即深度1中的所有元素).
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" (i.e., all the elements in depth 1).
例如:
输入对象:
{
"a":"val_a",
"b":
{
"b1":"val_b1",
"b2":"val_b2"
},
"c":
{
"c1":"val_c1",
"c2":
{
"c21":"val_c21",
"c22":"val_c22"
}
}
}
输出对象:
{
"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.
谢谢
一种替代方法是在Java中使用 JSON 框架,将您的JSON对象转换为Java,执行操作并生成新的JSON对象.
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.
抱歉造成误会.
您真的应该选择推荐的框架,例如一个或@Alessio.尽管可以通过使用正则表达式来实现 ,但我个人还是建议反对,因为您要查找的嵌套和/或对象有所变化可以带来正则表达式本身的巨大变化.因此,尽管正则表达式可以更快地完成工作,但它可能不那么易读和可维护.
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.