Creating Java Object with reserved keywords as variable name

后端 未结 3 1440
小蘑菇
小蘑菇 2020-12-12 00:08

I have JSON that needs to be converted to a Java Object. The JSONs I need to handle can look like this:

{
    \"documents\": [
        {
        \"title\": \         


        
相关标签:
3条回答
  • 2020-12-12 00:19

    If you use GSON for parsing you can name your members as you want and annotate them for mapping.

    @SerializedName("abstract")
    private String abstractText;
    
    0 讨论(0)
  • 2020-12-12 00:31

    In fact, it depends on the tool you are using. With tools mapping directly to your custom POJO (like GSON, Jackson), you need to map your JSON field name with your Java correct and valid field name.

    If you use a mors basic library such as JSON.org's, there is no need to do so because you parse it to specific object allowing you to handle it.

    JSONObject obj = new JSONObject(" .... ");
    
    JSONArray arr = obj.getJSONArray("documents");
    String abstractValue = arr.getJSONObject(0).getString("abstract");
    
    0 讨论(0)
  • 2020-12-12 00:43

    Another option you've got is to use Jackson, and use the @JsonProperty annotation..

    @JsonProperty("abstract")
    private String abstractText;
    
    0 讨论(0)
提交回复
热议问题