首页 > 解决方案 > 将字符串格式转换为列表 - 它不是 json 格式字符串

问题描述

如何将这种格式的字符串转换成列表?

[[["Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"]],[["example","text","thanks"]],[["name","surname","age"]]]

从那个字符串我想有3个列表:

清单 1:

"Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"
List 2:"example","text","thanks"
List 3:"name","surname","age"

我尝试了不同的方法来处理这个字符串,使用拆分,使用方法 StringUtils.substringBetween,使用 indexOf,使用正则表达式,使用 Json Parser....我总是得到一个错误,这是一个更简单的出路吗?

评论:我不认为这个字符串是 Json 格式,因为 Json 格式将是“name”:“John”,如果我错了,请告诉我如何将它作为 Json 处理......

我也尝试过使用 JsonParser 并在线程“main”java.lang.IllegalStateException 中出现异常:不是 JSON 对象:

[[["Census_county_divisions","Popula

标签: javastringarraylist

解决方案


我写了这段代码:

  1. 删除 [[[,]]] 字符串
  2. 替换 ]],[[ 为 | 特点
  3. 拆分字符串

    ///The String to convert
    String arg = "[[[\"Census_county_divisions\",.... 
    [[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
    
    System.out.println(arg);
    
    ////Replace 
    arg = arg.replace("[[[", "");
    arg = arg.replace("]],[[", "|");
    arg = arg.replace("]]]", "");
    
    System.out.println(arg);
    
    ////Split
    String[] array=arg.split("\\|");
    List<String> list =  Arrays.asList(array);
    
    ///Verify
    for(String s: list) {
        System.out.println(s);
    }
    

问候


推荐阅读