从json字符串中提取json

时间:2015-09-25 05:03:07

标签: java json

我从数据库中获取数据作为JSON字符串:

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

如何从给定的JSON字符串中提取公司名称?

4 个答案:

答案 0 :(得分:3)

参考JSON

JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
JSONObject companyName = jsonObject .get("companyName");

答案 1 :(得分:2)

JsonParser parser =  new JsonParser();
JsonElement jsonElement = parser.parse("your string");
JsonObject jsonObj = jsonElement.getAsJsonObject();
String comapnyName = jsonObj.get("companyName").getAsString();

这是我们在java中解析json字符串的方法。您需要添加com.google.gson库来编译此代码。

答案 2 :(得分: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);

答案 3 :(得分: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"));
相关问题