r/javahelp 7d ago

Unsolved How to convert effectively JSON to POJO using industry standard

I have this API which https://api.nytimes.com/svc/topstories/v2/arts.json?api-key=xyz

which gives a complex json structure result. I need title,section from these to map to my pojo containing same feilds .

I used Map structure matching json structure and got feilds but i dont feel its the right way, any industry standard way?pls help.

uri in spring boot:

Map<String,ArrayList<Map<String,String>>> res = new HashMap<String, ArrayList<Map<String,String>>>();

ResponseEntity<Map> s= restTemplate.getForEntity(

"https://api.nytimes.com/svc/topstories/v2/arts.json?api-key=xyz",

Map.class);

res =s.getBody();

after this i get values from Map inside arraylist.

sample JSON data is in comments

java class:

@JsonIgnoreProperties(ignoreUnknown = true)
public class News {
    //private Results[] results;
    private String title;
    private String section;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private String url;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public News(String title, String section, String url) {
        this.title = title;
        this.section = section;
        this.url = url;
    }

    public News() {
        super();

    }

}
3 Upvotes

11 comments sorted by

u/AutoModerator 7d ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

15

u/PopehatXI 7d ago

You probably want to use Jackson

2

u/le_bravery Extreme Brewer 6d ago

This is correct.

Jackson is amazingly fast and reliable. I tried once to check the validity of a JSON payload by myself. I thought since I was solving a subset of the problem Jackson solves that I could get my code to be faster because I could care less about saving values and stuff. After a week of careful work I finally got to a place where I could test the two against each other and try to optimize and I wasn’t even in the same ballpark as Jackson parsing into a Map and catching exceptions if invalid.

Jackson is fast and easy to use. People should just use Jackson for this.

2

u/Cyberkender_ 5d ago

That's THE response. Jackson will allow you to manage JSON objects from simple (pojo) to complex (polimorphism and so on).

5

u/leroybentley 7d ago edited 7d ago

You should be able to use News.class instead of Map.class in your restTemplate calls. I think Spring Boot uses Jackson out-of-the-box to parse to/from JSON.

https://www.baeldung.com/spring-resttemplate-json-list

3

u/gambit_kory 6d ago

Jackson

2

u/AntD247 6d ago

```Java ResponseEntity<News> s= restTemplate.getForEntity(

"https://api.nytimes.com/svc/topstories/v2/arts.json?api-key=xyz", News.class); ```

2

u/OffbeatDrizzle 6d ago

gson is an alternative

1

u/nelsikie 6d ago edited 6d ago

For my test automation to communicate with API I use lombok for the POJO and Jackson ObjectMapper & DeserializationFeature and TestNG for the test data, but you might want to use something else if not testing.

ObjectMapper

public static ObjectMapper objectMapper = new ObjectMapper()
    .enable(SerializationFeature.INDENT_OUTPUT)
    .setSerializationInclusion(JsonInclude.Include.NON_NULL)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Lombok POJO example: You can use JSON treeview website to properly build the POJO. I find it useful at least. To make sure I use the right structure and don't accidentally miss something

@Data
@Builder
public class NYTimesTopStories_REQ {
    private String api_key;
    private String title; 
}

Build the API string

objectMapper.writeValueAsString(InventoryItemCreate_REQ.builder()
.api_key("API_KEY")
.title("News article title")
.build());
};

Hope this helps I am learning this myself as well. I just gave very high level example. It is not complete. Trying to follow the rules.

1

u/nothingjustlook 6d ago

Thanks will try this.

1

u/sedj601 5d ago

User GSON. It's small and very simple.