0

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

Rohit Jain
  • 127
  • 3
  • 9

1 Answers1

2

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

ajc
  • 1,685
  • 14
  • 34
  • Thanks this can be one of an answer but this one is Brute force, I am looking for some optimise solution or any library.. – Rohit Jain Nov 29 '17 at 14:46