简体   繁体   中英

Trouble reading JSON from URL to java objects / storing in mysql db

I'm a newbie coder having just finished a 6 month coding crash-course. I'm working on a java webapp to demonstrate my skills, and the project idea I had involves retrieving JSON data from an API, something we didn't learn about in class. I made POJOs to match the JSON, and I'm trying to parse the JSON into java objects to store in a database, however my database tables are never filled with data when I run through the app. I suspect the problem is somewhere with my method to convert the JSON but any feedback is greatly appreciated. Here's all my code I think is relevant, sorry if its TMI. I also apologize if my code is ugly, I'm a beginner... Thanks!

API returns JSON like this:

{
    "result":{
        "status":1,
        "num_results":1,
        "total_results":500,
        "results_remaining":499,
        "matches":[{
            "match_id":3188095188,
            "match_seq_num":2784956606,
            "start_time":1495079320,
            "lobby_type":7,
            "radiant_team_id":0,
            "dire_team_id":0,
            "players":[{
                "account_id":86920222,
                "player_slot":0,
                "hero_id":18
             },{
                "account_id":61122568,
                "player_slot":1,
                "hero_id":85
             },{
                "account_id":10208661,
                "player_slot":2,
                "hero_id":13
             },{
                "account_id":106083675,
                "player_slot":132,
                "hero_id":50
             }]
         }]
    }
}

My POJOs:

@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Result {

    @JsonIgnore
    @Id
    @GeneratedValue
    private int id;

    @JsonProperty("status")
    private int status;

    @JsonProperty("num_results")
    private int num_results;

    @JsonProperty("total_results")
    private int total_results;

    @JsonProperty("results_remaining")
    private int results_remaining;

    @OneToMany
    @JoinColumn(name = "result_id")
    @ElementCollection(targetClass=Matches.class)
    @JsonProperty("matches")
    private List<Matches> matches;

    // getters and setters 
}

@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Matches {

    @Id
    @JsonProperty("match_id")
    private int match_id;

    @JsonIgnore
    @ManyToOne
    private Result result;

    @JsonProperty("match_seq_num")
    private int match_seq_num;

    @JsonProperty("start_time")
    private int start_time;

    @JsonProperty("lobby_type")
    private int lobby_type;

    @JsonProperty("radiant_team_id")
    private int radiant_team_id;

    @JsonProperty("dire_team_id")
    private int dire_team_id;

    @OneToMany
    @JoinColumn(name = "Matches_id")
    @ElementCollection(targetClass=Players.class)
    @JsonProperty("players")
    private List<Players> players;

    // getters and setters
}

@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Players {

    @JsonIgnore
    @Id
    @GeneratedValue
    private int id;

    @JsonIgnore
    @ManyToOne
    private Matches matches;

    @JsonProperty("account_id")
    private int account_id;

    @JsonProperty("player_slot")
    private int player_slot;

    @JsonProperty("hero_id")
    private int hero_id;

    // getters and setters
}

Services method to read and convert the JSON to objects (url is censored, don't want my API key to be public)

public class SteamService {
    public static Result getMatchHistory(String steamid){
        Result result = new Result();
        String MatchHistoryUrl = "https:**URL**="+steamid;
        RestTemplate restTemplate = new RestTemplate();
        Result jsonresult = restTemplate.getForObject(MatchHistoryUrl, Result.class);
        return jsonresult;
    }
}

Controller

@Controller
@RequestMapping("")
public class HomeController {
    @Autowired
    private ResultsDao resultsDao;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index(Model model){
        model.addAttribute("title", "Welcome");
        return "home/home";
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String processSteamIdField(@RequestParam("steamid")String steamid, Model model) {
        Result newresult = getMatchHistory(steamid);
        resultsDao.save(newresult);
        return "redirect:results";
    }
}

DAO

@Repository
@Transactional
public interface ResultsDao extends CrudRepository<Result, Integer>{
}

Maybe my approach is a bit naive, but... If you want to store the JSON as string in the database, then I would use an object mapper for this:

new ObjectMapper().writeValueAsString(myObject);

and for reading a JSON and parsing it to a class I would do:

new ObjectMapper().readValue(JSON_STRING_HERE, "utf-8"), MyPOJO.class);

Also, if you already are using Spring, then your controller may look like this (for a POST, for example)

@RequestMapping(value = "/", method = RequestMethod.POST)
public MyPojo myController(@RequestBody MyPojo myBody) {
    myRepository.save(myBody);
}

So, the parsing of the JSON that the client is sending to your app and your controller is already handled by Spring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM