【问题标题】:Java Splitting Arraylist from MapJava 从 Map 中拆分 Arraylist
【发布时间】:2014-11-18 10:39:55
【问题描述】:

我有一个从 mp 获得的数组列表,如下所示,

ArrayList<String> aList = (ArrayList<String>) jsonMap.get("govIds");

arraylist的大小为1,其内容是傻瓜,

[{govId=023402094, govIdType=TEST}]

如何使arraylist的大小为2,其中govId=023402094作为一个字符串对象,govIdType=TEST作为另一个字符串对象。

或如何将 [{govId=023402094, govIdType=TEST}] 作为键(字符串)-值(字符串)(又是映射)对。

谢谢

【问题讨论】:

  • 您想为govId=023402084 使用什么类型/类?对我来说,这看起来像是一个元组,而不是一个原语。
  • 可以是字符串类型
  • 列表必须是xxx=yyy的格式吗,可以是xxx:yyy吗?
  • @tjkmr,好的,看看我的回答是否有帮助!

标签: java json arraylist map


【解决方案1】:

试试这个:

    //here is the test data
    String s="[{govId=023402094, govIdType=TEST}]";
    List<String> aList =new ArrayList<String>();
    aList.add(s);
    //end of test data

    //Here is what you need begins   
    String text=aList.get(0).replaceAll("[\\[\\]\\{\\}]", "");// remove the char "{","}","[" and "]"
    //now the text is :govId=023402094, govIdType=TEST

    String[] values=text.split(",");
    List resultList=new ArrayList<String>();//Convert to another list, you can if you want to change a little to change into a map
    for(String value:values){
        resultList.add(value);
    }

   //test the result
    System.out.println(resultList);//[govId=023402094,  govIdType=TEST]

如果你的字符串格式看起来像 JSON {key1:value, key2:value2};您可以使用Gson 轻松将其更改为地图:

public static void main(String[] args){
    String s="[{govId:023402094, govIdType:TEST}]";// something like this
    String text=s.replaceAll("[\\[\\]]", "");// remove the char "[" and "]" to make it like as JSON format

    Map<String,String> map=toMapUsingGSON(text));

}

private static Map<String,String> toMapUsingGSON(String json){
    Type mapType = new TypeToken<Map<String, String>>(){}.getType();  
    return new Gson().fromJson(json, mapType);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2014-03-07
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多