如何从Json中提取值
我从服务器获得响应字符串,如下所示
{ "name": "Json", "detail": { "first_name": "Json", "last_name": "Scott", "age": "23" }, "status": "success" }
我想获得名字的价值。 我怎样才能做到这一点? 提前致谢。
看到这个代码我在我的应用程序中使用了什么
String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";
我这样检索过
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 );
在这里粘贴我的代码,这应该有所帮助。 它显示了可以使用的包装。
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); } }
如果您不介意添加依赖项,则可以使用JsonPath 。
import com.jayway.jsonpath.JsonPath; String firstName = JsonPath.read(rawJsonString, "$.detail.first_name");
“$”指定原始json字符串的根,然后您只需指定所需字段的路径。 这将始终返回一个字符串。 你必须自己做任何演员。
请注意,如果您指定的路径不存在,它将在运行时抛出PathNotFoundException。