在Java中,如何组合两个JSON对象数组? [英] In Java, how can I combine two JSON arrays of objects?

查看:325
本文介绍了在Java中,如何组合两个JSON对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个字符串,每个字符串包含一个对象数组的JSON表示。下面是代码中的示例,虽然这不是我的实际代码(传入JSON字符串):

I have several string each containing a JSON representation of an array of objects. Here's an example in code to illustrate, though this is not my actual code (the JSON strings are passed in):

String s1 = "[{name: "Bob", car: "Ford"},{name: "Mary", car: "Fiat"}]";
String s2 = "[{name: "Mack", car: "VW"},{name: "Steve", car: "Mercedes Benz"}]";

我需要将这两个JSON数组合并为一个大型JSON数组。我可以将其视为字符串操作问题,并用逗号替换内端方括号,但这不是特别健壮(尽管我保证获得有效的JSON)。

I need to combine those two JSON arrays into one large JSON array. I could treat this as a String manipulation problem and replace the inner end square brackets with commas but that's not particularly robust (though I am guaranteed to get valid JSON).

I我宁愿将这两个字符串视为JSON数组,只是以某种方式将它们组合在一起。这是一个很棒的计划,除了我不知道某种程度的部分。

I'd rather treat these two Strings as JSON arrays and just add them together somehow. It's a great plan except I don't know the "somehow" part.

有没有人知道Java中的解决方案不需要构建JSON的Java Object表示对象?

Does anyone know a solution in Java that doesn't require constructing Java Object representations of the JSON objects?

谢谢!

推荐答案

你真的只有两个选择:解析JSON(总是涉及构造对象)或不解析JSON。当然,解析不会更便宜。

You really have only two choices: parse the JSON (which invariably would involve constructing the objects) or don't parse the JSON. Not parsing is going to be cheaper, of course.

乍一看,你将它视为字符串操作问题的想法可能听起来很脆弱,但我想的越多它,它似乎越有意义。对于错误检测,您可以通过检查方括号轻松确认您确实在处理数组;之后,只需剥离结束括号,添加逗号,剥离开始括号,添加尾巴应该完美无缺。我能想到的唯一例外是,如果任一数组为空,则应该只返回另一个不变的字符串;再次,这很容易检查为字符串。

At first glance your idea about treating it as a String-manipulation problem might sound fragile, but the more I think about it, the more it seems to make fine sense. For error detection you could easily confirm that you were really dealing with arrays by checking for the square brackets; after that, just stripping off the ending bracket, adding a comma, stripping off the beginning bracket, and adding the "tail" should work flawlessly. The only exception I can think of is if either array is empty, you should just return the other String unchanged; again, that's very easy to check for as a String.

我真的认为没有任何理由让它变得更复杂。

I really don't think there's any reason to make it more complex than that.

这篇关于在Java中,如何组合两个JSON对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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