简体   繁体   English

如何从JAVA中的字符串(字符数组)中提取键值

[英]How to extract Key Value from String(Char Array) in JAVA

Sorry if some one ask this question earlier but I am unable to find relatively. 抱歉,如果有人早些时候问这个问题,但我却找不到。

My query is 我的查询是

String like this -> {"value":123,"key":abc}; 像这样的字符串-> {“ value”:123,“ key”:abc};

Change into => 变成=>

String str = ['"','v','a','l','u','e',':','1','2','3',',','k','e','y',':','a','b','c','"']; // char array

str[0] will be " , str[1] will be v str [0]将为“,str [1]将为v

So I want to know whether it is possible if i want to fetch value by this. 所以我想知道是否有可能我要借此获取价值。 let's say 比方说

str.getString("value") = 123  <- output expecting

things i tried: 我尝试过的事情:

1. JSONObject newStr = (JSONObject)JsonSerializer.toJSON(str);
2. Str.contains("key")
3. JSONObject newStr = new JSONObject(str);

but nothing work for me. 但对我没有任何帮助。 Can any one help me with that. 谁能帮我这个忙。

Is there any way so that i can get this answer like this. 有什么办法可以让我得到这样的答案。

str.get("value") = 123 and str.get("key") = abc str.get(“ value”)= 123和str.get(“ key”)= abc

Maybe updating the first and last element in the char array with { and } respectively. 也许分别用{}更新char数组中的第一个和最后一个元素。

Constructing a String from it. 从中构造一个字符串。

Parsing it in a JSONObject and then you can fetch what you want. 将其解析为JSONObject,然后可以获取所需的内容。

Sample code: 样例代码:

        Character[] str = {'{', 'v','a','l','u','e',':','1','2','3',',','k','e','y',':','a','b','c','}'};
        StringBuilder sb = new StringBuilder(str.length);
        for (Character c : str)
            sb.append(c.charValue());
        String strb = sb.toString();

        JSONObject obj = new JSONObject(strb);

        System.out.print(obj.get("value"));

Output 输出量

123 123

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

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