1

Let's say I have the following entity:

public class Employee {

  private String name;
  private Company company

}

And I have a String with the content below:

{
  "name":"Joe",
  "company": "http://localhost/companies/23"
}

Spring Data Rest is capable of converting this JSON to an Employee object out of the box, but to how convert it manually?

4
  • Why would I want to do something manually that is handled for me? what is your real question? Commented Jan 22, 2019 at 13:51
  • I have a problem similar to the one described in this issue. I need to implement a controller that receives both json data and files. The automatic conversion didn't work for me in this scenario, but I managed to receive the String containing the JSON, hence I would like to convert it manually. Commented Jan 22, 2019 at 13:58
  • I guess you should update your question to ask about that specific problem then. Commented Jan 22, 2019 at 14:53
  • Thank you, I understand your point. But I think this is still a valid question. Commented Jan 22, 2019 at 15:04

2 Answers 2

2

OK. I think I understand the problem now. Of course SDR has to have an ObjectMapper which is capable to convert the incoming JSON into an entity (including hateoas links), but it seems that's NOT the default ObjectMapper and it's not even exported as a Bean.

So I made some reverse-engineering and I think I've found what you need. Fortunately the ObjectMapper which is used internally has a public getter in the RepositoryRestMvcConfiguration class, so it can be used easily:

/**
 * The Jackson {@link ObjectMapper} used internally.
 *
 * @return
 */
public ObjectMapper objectMapper() {
    return mapper.get();
}

I think the following code will work:

@Autowired
RepositoryRestMvcConfiguration rrmc;

private <T> T readValue(String json, Class<T> type) 
    throws IOException, JsonParseException, JsonMappingException {
  return rrmc.objectMapper().readValue(json, type);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is exactly what I was looking for.
0
@Aurowired
private final RepositoryInvokerFactory repositoryInvokerFactory;

private Object loadPropertyValue(Class<?> type, String href) {
  String id = href.substring(href.lastIndexOf('/') + 1);
  RepositoryInvoker invoker = repositoryInvokerFactory.getInvokerFor(type);
  return invoker.invokeFindById(id).orElse(null);
}

1 Comment

Thank you for your contribution, although it helps a little, I don't think it fully anwers the question. I would like to convert the JSON as it is, without having to manually parse it.

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.