Tags
Tags

Reputation: 172

Assign variables from nested JSON string using Jackson

Wondering if anyone can help me figure out away to assign the body context to my description String variable.

Here is my JSON string

{"requirement":{"description":{"body":"This is a text"}}}

public class Requirement implements Serializable {

    private String description;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

I know I can use @JsonProperty("description") but my description is nested with different context. In this case I only care about the body.

Upvotes: 0

Views: 308

Answers (2)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

If you don't want to have the class with same structure as the json, you'll have to first unpack the description object and extract body:

public class Requirement {
private String body;

@JsonProperty("description")
private void unpackNested(Map<String,Object> description) {
    this.body = (String)description.get("body");
}

}

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32550

Your data structure actually looks like this

class Requirement{
  private Description description;
}
class Description{
  private String body;
}

just add proper @JsonProperty and you will be fine.

In general, every json Object is a separate class (unless you map to plan maps)

Upvotes: 1

Related Questions