Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java native JSON api for parsing

Tags:

java

json

I've following JSON structure coming in,

{
  "name": "product new",
  "brand": {
    "id": 1
  },
  "category": {
    "id": 1
  }
}

I can extract

jsonObject = Json.createReader(httpServletRequest.getInputStream()).readObject();
jsonObject.getString("name")

Errors:

jsonObject.getInt("brand.id")
jsonObject.getInt("category.id")

I'm using Java API for JSON.

Edit If I access

System.out.println(jsonObject.get("brand"));
// response {"id":1}

System.out.println(jsonObject.get("brand.id"));
// null

http://www.oracle.com/technetwork/articles/java/json-1973242.html

like image 415
user2727195 Avatar asked Oct 22 '25 15:10

user2727195


1 Answers

I don't think the API you're using supports nested expressions. You'll need to access the parent object, and then the specific field:

System.out.println(jsonObject.getJsonObject("brand").getInt("id"));

Or you can use an API that accepts a path expression, like Jackson:

JsonNode node = new ObjectMapper().readTree(httpServletRequest.getInputStream());
System.out.println(node.at("/brand/id").asInt());
like image 151
shmosel Avatar answered Oct 25 '25 06:10

shmosel