1

I am fetching data from the database as a JSON String:

{"companyName":"abcd","address":"abcdefg"}

How can I extract the company name from the given JSON String?

1
  • Do you mean how to work with JSON in Java? It seems unclear what you are asking about. I made this assumption only because of java tag. Commented Sep 25, 2015 at 5:06

4 Answers 4

3

Refer JSON

JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
JSONObject companyName = jsonObject .get("companyName");
Sign up to request clarification or add additional context in comments.

2 Comments

Although you did provide a link to some javadoc, you didn't explain that this requires installing a third-party jar file in order to work, or where to find such file.
You can download the code from Here compile it and create a jar. Adding this jar should make these classes available.
2
JsonParser parser =  new JsonParser();
JsonElement jsonElement = parser.parse("your string");
JsonObject jsonObj = jsonElement.getAsJsonObject();
String comapnyName = jsonObj.get("companyName").getAsString();

This is how we can parse json string in java. You will need to add com.google.gson library to compile this code.

2 Comments

There is no JsonParser is the Java Standard Library. This code won't compile.
@Andreas: Thanks for remind me. I have updated the library.
2

JSONObject obj = new JSONObject();

  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));

  StringWriter out = new StringWriter();
  obj.writeJSONString(out);

Comments

1
JSONObject json = (JSONObject)new JSONParser().parse("{\"companyName\":\"abcd\", \"address\":\"abcdefg\"}");
System.out.println("companyName=" + json.get("companyName"));
System.out.println("address=" + json.get("address"));

2 Comments

The question is about Java, not JavaScript.
I have edited my answer ,I think this Gonna work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.