Search code examples
javaandroidjsonunirestmashape

How to parse JSON results from Unirest call


I'm using the Unirest library to retrieve JSON from a Mashape API. I have the call working using the following code:

HttpResponse<JsonNode> request = Unirest.get(URL)
  .header("X-Mashape-Authorization", MASHAPE_AUTH)
  .asJson();

This returns my JSON in the form of HttpResponse<JsonNode>, which I am unfamiliar with.

From reading the limited documentation, It seems that I have to call getBody() on the response object in order to get a JsonNode object back. I still have no idea what to do with the JsonNode object however.

What is the best way to begin to parse this data?

Edit: In case it helps with giving examples, the JSON I want to parse looks like this:

{
  "success": "1",
  "error_number": "",
  "error_message": "",
  "results": [
    {
      "name": "name1",
      "formatedName": "Name 1"
    },
    {
      "name": "testtesttest",
      "formatedName": "Test Test Test"
    },
    {
      "name": "nametest2",
      "formatedName": "Name Test 2"
    },
    {
      "name": "nametest3",
      "formatedName": "Name Test 3"
    }
  ]
}

Solution

  • Was trying to figure this out today for myself. The source code is probably the only documentation you're going to get. Here's the tl;dr

    // the request from your question
    HttpResponse<JsonNode> request = Unirest.get(URL)
      .header("X-Mashape-Authorization", MASHAPE_AUTH)
      .asJson();
    
    // retrieve the parsed JSONObject from the response
    JSONObject myObj = request.getBody().getObject();
    
    // extract fields from the object
    String msg = myObj.getString("error_message");
    JSONArray results = myObj.getJSONArray();
    

    Here's some more explanation of the spelunking I did:

    From the HttpResponse class we can see that getBody() is going to return the instance variable body, which gets assigned on line 92 as:

    this.body = (T) new JsonNode(jsonString)
    

    So then we need to look at the JsonNode class. The constructor takes a string representing the JSON to be parsed and attempts to create either a JSONObject or a JSONArray. Those objects come from org.json which is well documented, thankfully.