0

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.

7
  • Not sure that I understand your question correctly. You can simply parse you JSON and extract whatever you want from it, but seems it is not what you are looking for? Commented Dec 14, 2018 at 18:55
  • 1
    You should have a RequirementModel, a DescriptionModel and a BodyModel, and in DescriptionModel there is a private BodyModel body; and then extract the string from the BodyModel object. Commented Dec 14, 2018 at 18:58
  • I just edited my question. I wrote the json incorrectly Commented Dec 14, 2018 at 19:00
  • @cokeby190 Thats what I have done. I have a model/POJO for Requirements, description, etc. Im just wondering instead of creating a POJO for Description just assign the body to a description string in requirement POJO Commented Dec 14, 2018 at 19:04
  • Ah I see, this part I am not too familiar with sorry! Commented Dec 14, 2018 at 19:05

2 Answers 2

1

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");
}

}

Sign up to request clarification or add additional context in comments.

3 Comments

What is (String)brand.get("body")? Im getting an error on brand
Edited it, check.
Maybe not but sometimes its required to map to different variables
1

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)

2 Comments

Yes I know but I want to avoid this by just assigning the body of description to a variable in requirement POJO.
This is how Jackson work. Your requirement is some sort of rare modeling issue that. Since this is exact reflection of your data model - change the model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.