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?

Stimpson Cat
  • 1,444
  • 19
  • 44
  • use gson.jar or json.jar. They have constructors for JsonObject, in which you can pass string. [Here is the link](https://repo1.maven.org/maven2/com/google/code/gson/gson/2.6.2/) – AmitB10 Aug 04 '17 at 11:00
  • Pleaese look at this answer https://stackoverflow.com/questions/5128442/how-to-convert-a-string-to-jsonobject-using-gson-library – Stimpson Cat Aug 04 '17 at 11:02

3 Answers3

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.

Houssam Badri
  • 2,441
  • 3
  • 29
  • 60
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

Bhavik Patel
  • 1,044
  • 1
  • 15
  • 33
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.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102