0

I have a Java String that contains a json object and I do not know how to get this json object from it?

My string is like this:

String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";

How can i get the json object from this String?

2

3 Answers 3

1

I would recommend simple plain org.json library. Pass the string in JSONArray and then get the JSONObject. For example something like below :

String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
JSONArray js = new JSONArray(myString);
System.out.println(js);
JSONObject obj = new JSONObject(js.getString(1));
System.out.println(obj);

Output :

  • [1,"{\"Status\":0,\"InstanceNumber\":9}"]
  • {"Status":0,"InstanceNumber":9}

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

Sign up to request clarification or add additional context in comments.

Comments

1

For sure that you need to use a library lie Jackson or Gson.

I work mostly with gson when I don't have complicated stuff. So here the output of what you are asking for. I suppose that you don't have the type that you want to convert to (for that I am taking Object).

Here is the code:

import com.google.gson.Gson;

public class Json {

    public static void main(String[] args) {
       Gson g = new Gson();
       String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
       Object p = g.fromJson(myString, Object.class);
       System.out.println(p.toString());
    }

}

And here is the output :

run:
[1.0, {"Status":0,"InstanceNumber":9}]
BUILD SUCCESSFUL (total time: 0 seconds)

You may wanting to manipulate the output object as you wish (I just printed it out). NOTE: Don't forget to add gson jar to you classpath.

1 Comment

Nailed it, Excellent
0

You can use any Json mapping framework to deserialise the String into Java object. Below example shows how to do it with Jackson:

String myString = "[1,\"{\\\"Status\\\":0,\\\"InstanceNumber\\\":9}\"]";
ObjectMapper mapper = new ObjectMapper();
List<Object> value = mapper.readValue(myString, new TypeReference<List<Object>>() {});
Map<String, Object> map = mapper.readValue(value.get(1).toString(), new TypeReference<Map<String, Object>>() {});
System.out.println(map);

Here's the documentation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.