22

I am getting a response String from server like below

{ "name": "Json", "detail": { "first_name": "Json", "last_name": "Scott", "age": "23" }, "status": "success" } 

I want to get the value of First name. How can I do that?

0

9 Answers 9

22

see this code what i am used in my application

String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}"; 

I retrieved like this

JSONObject json = (JSONObject) JSONSerializer.toJSON(data); double coolness = json.getDouble( "coolness" ); int altitude = json.getInt( "altitude" ); JSONObject pilot = json.getJSONObject("pilot"); String firstName = pilot.getString("firstName"); String lastName = pilot.getString("lastName"); System.out.println( "Coolness: " + coolness ); System.out.println( "Altitude: " + altitude ); System.out.println( "Pilot: " + lastName ); 
Sign up to request clarification or add additional context in comments.

7 Comments

Which library did you use??
Btw: That is not a valid json string for data. You have to use " " vs. ' ' . It can be validated on this jsonlint.com
@Parzifal Download this library: java2s.com/Code/Jar/j/Downloadjsonlibjar.htm and follow the steps described in this answer stackoverflow.com/a/8997703/4980043 . Do not use the library linked in the referenced answer because it does not include the JSONSerializer class.
which library did you use for JSONSerializer?
@KarenGonzalez Looks like this link not working anymore. <a>java2s.com/Code/Jar/j/Downloadjsonlibjar.htm</a>
|
14

Pasting my code here, this should help. It shows the package which can be used.

import org.json.JSONException; import org.json.JSONObject; public class extractingJSON { public static void main(String[] args) throws JSONException { // TODO Auto-generated method stub String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"}}"; JSONObject jsonObj = new JSONObject(jsonStr); String name = jsonObj.getString("name"); System.out.println(name); String first = jsonObj.getJSONObject("arr").getString("a"); System.out.println(first); } } 

Comments

7

If you don't mind adding a dependency, you can use JsonPath.

import com.jayway.jsonpath.JsonPath; String firstName = JsonPath.read(rawJsonString, "$.detail.first_name"); 

"$" specifies the root of the raw json string and then you just specify the path to the field you want. This will always return a string. You'll have to do any casting yourself.

Be aware that it'll throw a PathNotFoundException at runtime if the path you specify doesn't exist.

1 Comment

Good to know about this library, excellent for scraping Json embedded into web pages.
1
String jsonErrorString=((HttpClientErrorException)exception).getResponseBodyAsString(); JSONObject jsonObj=null; String errorDetails=null; String status=null; try { jsonObj = new JSONObject(jsonErrorString); int index =jsonObj.getString("detail").indexOf(":"); errorDetails=jsonObj.getString("detail").substring(index); status=jsonObj.getString("status"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } item.put("status", status); item.put("errordetailMsg", errorDetails); 

Comments

1

if you receive a response String formated like json, you can do:

import org.json.simple.parser.JSONParser; JSONParser parser = new JSONParser(); JSONObject jsonResponse = (JSONObject) parser.parse(response); 

then to get the name :

String name = (String) jsonObject.get("name"); 

to get the firstname :

JSONObject detailObject = (JSONObject) jsonObject.get("detail"); String firstname = (String) detailObject.get("first_name"); 

Comments

0
 JSONArray ja = new JSONArray(json); JSONObject ob = ja.getJSONObject(0); String nh = ob.getString("status"); 

[ { "status" : "true" } ]

where 'json' is a String and status is the key from which i will get value

Comments

0

we can use the below to get key as string from JSON OBJECT

JsonObject json = new JsonObject(); json.get("key").getAsString(); 

this gives the string without double quotes " " in the string

Comments

-1
 //import java.util.ArrayList; //import org.bson.Document; Document root = Document.parse("{\n" + " \"name\": \"Json\",\n" + " \"detail\": {\n" + " \"first_name\": \"Json\",\n" + " \"last_name\": \"Scott\",\n" + " \"age\": \"23\"\n" + " },\n" + " \"status\": \"success\"\n" + "}"); System.out.println(((String) root.get("name"))); System.out.println(((String) ((Document) root.get("detail")).get("first_name"))); System.out.println(((String) ((Document) root.get("detail")).get("last_name"))); System.out.println(((String) ((Document) root.get("detail")).get("age"))); System.out.println(((String) root.get("status"))); 

Comments

-1

If you want to use the standard library Jackson, you can read the json string and store it as a JsonNode.

final String json = "{\"name\": \"asdf\", \"age\": \"23\", }"; final JsonNode node = new ObjectMapper().readValue(json, JsonNode.class); System.out.println(jsonNode.findValuesAsText("name")); 

If you want to store the json object as a map then you may use ObjectNode (which is a Map implementation of JsonNode). You can get elements by key as shown below.

final ObjectNode node = new ObjectMapper().readValue(json, ObjectNode.class); if (node.has("name")) { System.out.println("name: " + node.get("name")); } 

If you want to store the json object as an Array then you may use ArrayNode (which is an Array implementation of JsonNode). You can get elements by index as shown below.

final ObjectNode node = new ObjectMapper().readValue(json, ObjectNode.class); System.out.println("name: " + node.get(0)); 

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.