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?

Vishal
  • 549
  • 1
  • 4
  • 21
user3415447
  • 101
  • 3
  • 13

4 Answers4

3

Refer JSON

JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
JSONObject companyName = jsonObject .get("companyName");
Rahul Yadav
  • 1,503
  • 8
  • 11
  • 1
    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. – Andreas Sep 25 '15 at 05:16
  • You can download the code from [Here](https://github.com/douglascrockford/JSON-java) compile it and create a jar. Adding this jar should make these classes available. – Rahul Yadav Sep 25 '15 at 05:46
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.

Kruti Patel
  • 1,422
  • 2
  • 23
  • 36
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);
Prakash Bisht
  • 226
  • 1
  • 10
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"));
Shardendu
  • 3,480
  • 5
  • 20
  • 28