简体   繁体   中英

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};

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

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

Maybe updating the first and last element in the char array with { and } respectively.

Constructing a String from it.

Parsing it in a JSONObject and then you can fetch what you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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