简体   繁体   English

如何在Java中将复杂的字符串转换为列表/数组?

[英]How to convert a complex string to a list / array in Java?

I know using myString.split(","); 我知道使用myString.split(","); would work if I just had a string separated by commas like "a", "b", "c" , but what if I have a more complicated string like: 如果我只有一个用逗号分隔的字符串,如"a", "b", "c" ,则可以工作,但是如果我有一个更复杂的字符串,如:

["Meal End", "meal-end", "menu", {"color":"black", "width":1}] [“餐点”,“餐点”,“菜单”,{“颜色”:“黑色”,“宽度”:1}]

I want to separate out the elements 我想把元素分开

"Meal End" “用餐结束”

"meal-end" “饭端”

"menu" “菜单”

{"color":"black", "width":1} {“颜色”:“黑色”,“宽度”:1}

My first approach was to get a substring of that whole thing from (1 to string.length - 1). 我的第一种方法是从(1到string.length-1)获取整个内容的子字符串。 That removed the [ ]. 删除了[]。 Then I used string.split(",") which almost worked... but for element 3 I end up with {"color":"black" which I do not want. 然后,我使用了string.split(“,”),它几乎可以工作...但是对于元素3,我最终得到了我不想要的{“ color”:“ black”。

I want the whole curly brackets object. 我想要整个花括号对象。 How can I do this, other than manually searching through the whole string, stopping when I find a {, and continuing when I get to }? 除了手动搜索整个字符串,在找到{时停止并在到达}时继续之外,我该如何做?

I considered using JSONObject but my string is enclosed in [ ] ... I could always replace those with { } but then there's no key still... 我考虑过使用JSONObject,但是我的字符串包含在[]中。我总是可以用{}替换它们,但是仍然没有键...

I would suggest "jackson". 我建议“杰克逊”。 It parses this string as a list containing 3 strings and 1 map. 它将此字符串解析为包含3个字符串和1个映射的列表。

List<?> value = (List<?>) new ObjectMapper().readValue(
    "[\"Meal End\", \"meal-end\", \"menu\", {\"color\":\"black\", \"width\":1}]", 
    Object.class);
System.out.println(value.get(0));
Map<?, ?> map = (Map<?, ?>) value.get(3);
System.out.println(map.get("color"));

Output: 输出:

Meal End 
black

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

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