java - 从 URL 读取 JSON 到 java 对象/存储在 mysql 数据库中时遇到问题

标签 java mysql json

我是一名新手编码员,刚刚完成了为期 6 个月的编码速成类(class)。我正在开发一个 java web 应用程序来展示我的技能,我的项目想法涉及从 API 检索 JSON 数据,这是我们在类里面没有学到的。我制作了 POJO 来匹配 JSON,并且尝试将 JSON 解析为 java 对象以存储在数据库中,但是当我运行应用程序时,我的数据库表从未填充数据。我怀疑问题出在我转换 JSON 的方法上,但非常感谢任何反馈。这是我认为相关的所有代码,抱歉,如果是 TMI。如果我的代码很丑陋,我也深表歉意,我是初学者......谢谢!

API 返回 JSON 如下:

{
    "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
             }]
         }]
    }
}

我的 POJO:

@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
}

读取 JSON 并将其转换为对象的服务方法(网址经过审查,不希望我的 API key 公开)

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>{
}

最佳答案

也许我的方法有点天真,但是...如果您想将 JSON 作为字符串存储在数据库中,那么我会为此使用对象映射器:

new ObjectMapper().writeValueAsString(myObject);

为了读取 JSON 并将其解析为一个类,我会这样做:

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

此外,如果您已经在使用 Spring,那么您的 Controller 可能如下所示(例如,对于 POST)

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

因此,客户端发送到您的应用程序和 Controller 的 JSON 的解析已由 Spring 处理

关于java - 从 URL 读取 JSON 到 java 对象/存储在 mysql 数据库中时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44080864/

相关文章:

ruby-on-rails - Rails 渲染带有驼峰命名法的 json 对象

java - 有没有办法将 Java TreeMap 序列化为 JSON?

javascript - Ionic3 需要重新加载才能显示 json

java - CsrfGuard 出现问题。尽管从官方网站进行了配置,csrf 仍抛出问题

java - 错误: "org.apache.axis2.AxisFault: Transport error: 403 Error: Forbidden"

c# - 从日期时间到当前时区的 Unix 纪元时间的转换

php - 无法获取对 bool 值上的成员函数 fetch_row() 的行调用

java - JPA EntityGraph 不工作;始终加载相关集合

mysql - 如何确定 MySQL 中的最大事务大小?

php - MysQl 错误 : Invalid parameter number