wrongusername
wrongusername

Reputation: 18918

How can I only return some fields in the JSON object?

I currently have a function that returns a JSON version of an object:

public class Debate extends Controller
{
    public static Result viewArgument(Long id)
    {
        ...
        return ok(Json.toJson(Argument.get(id)));
    }
}

This Argument object has some confidential information that should not be exposed to the client, however. How can I select only the fields id and summary to be returned in the resulting JSON object?

Upvotes: 0

Views: 616

Answers (2)

Shanness
Shanness

Reputation: 395

There is a simpler answer, just add @JsonIgnore to the other fields.

Upvotes: 1

Dennis Traub
Dennis Traub

Reputation: 51654

You can copy the Argument's idand summary into a DTO (Data Transfer Object). Then turn that into JSON to be sent over the wire.

public class ArgumentDto {
    public Long id;
    public String summary;
}

public class Debate extends Controller
{
    public static Result viewArgument(Long id)
    {
        ...
        Argument originalArgument = Argument.get(id);
        ArgumentDto argument = new ArgumentDto();
        dto.id = originalArgument.id;
        dto.summary = originalArgument.summary;
        return ok(Json.toJson(dto));
    }
}

Upvotes: 1

Related Questions