Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android将字符串转换为HashMap_Java_Android_Regex_Json - Fatal编程技术网

Java Android将字符串转换为HashMap

Java Android将字符串转换为HashMap,java,android,regex,json,Java,Android,Regex,Json,我有一个类似这样的字符串: 结构是{“key”:value}。我需要将其转换为表/哈希映射,以便根据键获取值 我尝试使用Gson,但失败了。有没有一种更简单的方法可以像使用序列化一样来实现这一点 TIA编写自己的简单解析器。从开始读取每个字符,当您看到“然后开始将下一个字符的开始视为键的开始,并在出现下一个”时,现在开始读取键在这一点上查找:然后记录值,直到您看到空白或}。再次重复此过程,直到读取了字符串中的所有字符。这样,如果有n个字符,那么它将在O(n)中求解。使用我提出的方法: publ

我有一个类似这样的字符串:

结构是
{“key”:value}
。我需要将其转换为表/哈希映射,以便根据键获取值

我尝试使用Gson,但失败了。有没有一种更简单的方法可以像使用序列化一样来实现这一点


TIA

编写自己的简单解析器。从开始读取每个字符,当您看到“然后开始将下一个字符的开始视为键的开始,并在出现下一个”时,现在开始读取键在这一点上查找:然后记录值,直到您看到空白或}。再次重复此过程,直到读取了字符串中的所有字符。这样,如果有n个字符,那么它将在O(n)中求解。

使用我提出的方法:

public HashMap<String, Integer> convertToHashMap(String jsonString) {
        HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
        try {
            JSONArray jArray = new JSONArray(jsonString);
            JSONObject jObject = null;
            String keyString=null;
            for (int i = 0; i < jArray.length(); i++) {
                jObject = jArray.getJSONObject(i);
                // beacuse you have only one key-value pair in each object so I have used index 0 
                keyString = (String)jObject.names().get(0);
                myHashMap.put(keyString, jObject.getInt(keyString));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return myHashMap;
    }
public HashMap convertToHashMap(字符串jsonString){
HashMap myHashMap=新HashMap();
试一试{
JSONArray jArray=新的JSONArray(jsonString);
JSONObject jObject=null;
字符串keyString=null;
for(int i=0;i
使用:

String myString=“[{\'1\':33},{\'2\':30},{\'3\':15},{\'4\':23},{\'9\':17},{\'U\':2},{\'V\':22},{\'W\':1},{\'X\':35},{'Y\':6},{\'Z\:19}”;
HashMap=convertToHashMap(myString);
Log.d(“test”,map.toString());

您还可以使用
map.keySet()

获取所有键。您有一个对象数组,每个对象都不同(它有一个不同的字段)。JSON解析器在谈到将其反序列化为对象时会遇到问题。Gson用户指南

您可以使用Gson,但必须使用他们建议的方法之一。创建一个返回
Map
的自定义反序列化程序相当简单。您需要遍历数组,获取每个对象,然后提取字段和值:

// create this class so as not to affect other Map types:
class MyMap extends HashMap<String, Integer> {}

class MyMapDeserializer implements JsonDeserializer<MyMap> 
{
    public MyMap deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) 
          throws JsonParseException 
    {
        JsonArray ja = je.getAsJsonArray();
        MyMap map = new MyMap();
        for (int i = 0; i < ja.size(); i++) 
        {
            JsonObject jo = ja.get(i).getAsJsonObject();
            Set<Entry<String, JsonElement>> set = jo.entrySet();
            for (Entry<String, JsonElement> e : set) 
            {
                map.put(e.getKey(), e.getValue().getAsInt());
            }
        }
        return map;
    }
}

可以使用正则表达式使用此代码:

    Map<String, String> map = new HashMap<String, String>();
    //!!Your string comes here, I escape double quoutes manually !!
    String str = "\"[ { \"1\":33 }, { \"2\":30 }, { \"3\":15 }, { \"4\":23 }, { \"9\":17 }, {\"U\":2 }, { \"V\":22 }, { \"W\":1 }, { \"X\":35 }, { \"Y\":6 }, { \"Z\":19 } ]\"";
    String regex = "\\{\\s*\"(\\w+)\":(\\d+)\\s*\\}";


    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        String key = matcher.group(1);
        String value = matcher.group(2);
        System.out.println(key + " " + value);
        map.put(key, value);
    }

注意:如果需要
Map
则更改定义并使用
Integer.parseInt()
从字符串中获取整数。

这是JSON格式。。因此,请使用JSON并将这些JSON对象放在HashMapSee中。仅使用Regexe的工作代码具有不同的首字母string@NikolayKuznetsov这不是他上面写的字符串。@NikolayKuznetsov你的代码在添加什么\这也不是初始字符串。你听说过转义特殊字符吗?尝试定义'String s=“{1:33}”;在爪哇
public static void main(String[] args) {
    String s = "{ 1:33 }, { 2:30 }, { 3:15 }, { 4:23 }, { 9:17 }, { U:2 }, { V:22 }, { W:1 }, { X:35 }, { Y:6 }, { Z:19 }";
    String[] arr = s.split(", ");
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String str : arr) {
        str = str.replace("{", "").replace("}", "");
        String[] splited = str.split(":");

        map.put(splited[0], Integer.parseInt(splited[1].trim()));

    }
    System.out.println(map);

}
    Map<String, String> map = new HashMap<String, String>();
    //!!Your string comes here, I escape double quoutes manually !!
    String str = "\"[ { \"1\":33 }, { \"2\":30 }, { \"3\":15 }, { \"4\":23 }, { \"9\":17 }, {\"U\":2 }, { \"V\":22 }, { \"W\":1 }, { \"X\":35 }, { \"Y\":6 }, { \"Z\":19 } ]\"";
    String regex = "\\{\\s*\"(\\w+)\":(\\d+)\\s*\\}";


    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        String key = matcher.group(1);
        String value = matcher.group(2);
        System.out.println(key + " " + value);
        map.put(key, value);
    }
1 33
2 30
3 15
4 23
9 17
U 2
V 22
W 1
X 35
Y 6
Z 19
public static void main(String[] args) {
    String s = "{ 1:33 }, { 2:30 }, { 3:15 }, { 4:23 }, { 9:17 }, { U:2 }, { V:22 }, { W:1 }, { X:35 }, { Y:6 }, { Z:19 }";
    String[] arr = s.split(", ");
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String str : arr) {
        str = str.replace("{", "").replace("}", "");
        String[] splited = str.split(":");

        map.put(splited[0], Integer.parseInt(splited[1].trim()));

    }
    System.out.println(map);

}
{ 9=17,  Z=19,  Y=6,  X=35,  1=33,  3=15,  2=30,  W=1,  V=22,  4=23,  U=2}