How do I extract value from Json

前端 未结 8 1116
野的像风
野的像风 2020-11-30 05:23

I am getting a response String from server like below

{
  \"name\": \"Json\",
  \"detail\": {
    \"first_name\": \"Json\",
    \"last_name\": \"Scott\",
            


        
8条回答
  •  暖寄归人
    2020-11-30 05:36

    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.

提交回复
热议问题