1

I'm NOT Java developer, but right now I'm writing some tests with it, and I'm stuck with simple issue (I suppose it's simple for "javaGuys").

In my class Test I'm getting variable that contain some string that LOOKS LIKE OBJECT in JavaScript(I mean JSON). Here it is:

String myStringThatLooksLikeJSON = client.getStartSessionContent();

In debug mode that string's content...:

myStringThatLooksLikeJSON = "{"context":"blabla","count":0,"value":[{"args":"speech-model","id":"1203"}]}"

And now my question. How can I get just value of, for example, "args"?

In JavaScript it can be done easily like:

console.log(myStringThatLooksLikeJSON.value[0].args, "args");

And in my console I can see speech-model args.

But how to do that in Java? Is it possible? THE MOST PURE COMMON AND SIMPLE WAY! Plz anyone help :) Hope I was clear enough.

impregnable fiend
  • 289
  • 1
  • 5
  • 16

4 Answers4

5

Use Gson (or jackson) to parse your json string to a java object:

YourClass object=new Gson().fromjson(myStringThatLooksLikeJSON,YourClass.class);

the YourClass need to describes your json fields.

see JSON parsing using Gson for Java for a direct access to your desired field

Community
  • 1
  • 1
Tokazio
  • 516
  • 2
  • 18
5

OR you can use simple JSON java package

String data = "{\"context\":\"blabla\",\"count\":0,\"value\":[{\"args\":\"speech-model\",\"id\":\"1203\"}]}";
JSONObject d = new JSONObject(data);
System.out.println(d.getJSONArray("value").getJSONObject(0).getString("args"));
Bhavik Patel
  • 1,044
  • 1
  • 15
  • 33
1

Because there isn't any JSON parser in standard JDK you have to rely on external libraries.

There are many other

fustaki
  • 1,574
  • 1
  • 13
  • 20
0

Add a Jackson dependency to your project. Here is the dependency you can add if you build your project with maven.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.6</version>
</dependency>

Create an Object that contains keys of JSON as fields. Using the following, you can convert Json into Java object and access the filed you need.

ObjectMapper mapper = new ObjectMapper();
SampleClass obj = mapper.readValue(jsonInString, SampleClass.class);
AV94
  • 1,824
  • 3
  • 23
  • 36
  • Note that the OP never said he was using Maven. I'd post the "standard way" too (adding the jar to classpath) for completeness – BackSlash Feb 16 '17 at 12:24