将 JSON 映射到 Java 类

问题描述 投票:0回答:1

我想将 JSON 输出映射到 Java 类 这是对 REST API 请求的响应。我附上了一些我遇到问题的 JSON。它是较大文件的较小部分。 问题是它不是标准属性/值对,例如

"color" : "red"

看起来像这样:

{"transactions" : {
         "transaction_id_005" : {
            "complete" : false,
            "confirmed" : false,
            "event_transaction_id" : "transaction_id_005_11223344_1714400505026_SWupdate-000002",
            "event_type" : "software_update",
            "expiration_mark" : false}
   }
}

这是我的代码。


Transaction trans = new Gson().fromJson(transstring, Transaction.class);
        }
        
        catch (Exception e) {
            System.out.println(e.getMessage());
        }

和课程:

public class Transaction {
    
    public String transactions = "";
    public Embedded embedded = null;
    public String getTransactions() {
        return transactions;
    }
    public void setTransactions(String transactions) {
        this.transactions = transactions;
    }
    public Embedded getEmbedded() {
        return embedded;
    }
    public void setEmbedded(Embedded embedded) {
        this.embedded = embedded;
    }
}

class Embedded {
    public String complete ="";
    public String confirmed ="";
    public String event_transaction_id = "";
    public String event_type = "";
    public String expiration_mark = "";
}

它抛出这个异常: gson.JsonSyntaxException:java.lang.IllegalStateException:需要一个字符串,但在第1行第20列路径$.transactions

处是BEGIN_OBJECT

我发现这意味着它不希望在“交易”之后的第一行中打开 { :

java gson pojo
1个回答
0
投票

json 的表示是一个类事务,其属性事务是一个映射

import java.util.Map;

import com.google.gson.Gson;

public class Transaction {
    
    public Map<String,Embedded> transactions; 
    public Map<String,Embedded> getTransactions() {
        return transactions;
    }
    public void setTransactions(Map<String,Embedded> transactions) {
        this.transactions = transactions;
    }


    public static void main(String[] argv) {
        Transaction trans = new Gson().fromJson("{\"transactions\" : {\r\n"
                + "         \"transaction_id_005\" : {\r\n"
                + "            \"complete\" : false,\r\n"
                + "            \"confirmed\" : false,\r\n"
                + "            \"event_transaction_id\" : \"transaction_id_005_11223344_1714400505026_SWupdate-000002\",\r\n"
                + "            \"event_type\" : \"software_update\",\r\n"
                + "            \"expiration_mark\" : false}\r\n"
                + "   }\r\n"
                + "}", Transaction.class);

        System.out.println(trans);
    
    }

}

class Embedded {
    public String complete ="";
    public String confirmed ="";
    public String event_transaction_id = "";
    public String event_type = "";
    public String expiration_mark = "";
}
© www.soinside.com 2019 - 2024. All rights reserved.