Конвертировать json в Java Object - для свойства установлено значение Null - PullRequest
0 голосов
/ 01 февраля 2019

Я пытаюсь преобразовать Json в объект Java. У меня есть строка с именем result , и я хочу преобразовать ее в объект Java, класс которого TransferRecord.java

Это часть строки, которую я использую в качестве ввода.

{
  "TransferRecord": {
    "TransferId": {
      "TransferRef": "string",
      "DistributorRef": "string"
    },
    "SkuCode": "string",
    "Price": {
      "CustomerFee": 0,
      "DistributorFee": 0,
      "ReceiveValue": 0,
      "ReceiveCurrencyIso": "string",
      "ReceiveValueExcludingTax": 0,
      "TaxRate": 0,
      "TaxName": "string",
      "TaxCalculation": "string",
      "SendValue": 0,
      "SendCurrencyIso": "string"
    },
    "CommissionApplied": 0,
    "StartedUtc": "2019-01-31T10:10:20.527Z",
    "CompletedUtc": "2019-01-31T10:10:20.527Z",
    "ProcessingState": "string",
    "ReceiptText": "string",
    "ReceiptParams": {},
    "AccountNumber": "string"
  },
  "ResultCode": 0,
  "ErrorCodes": [
    {
      "Code": "string",
      "Context": "string"
    }
  ]
}

Это класс TransferRecord.Я проверил сопоставление json, и они полностью идентичны. Обратите внимание, что в классе доступно больше полей, но я просто вставил его часть. Количество свойств во входной строке и классе java одинаковы.

public class TransferRecord   {
  @JsonProperty("TransferId")
  private TransferId transferId = null;

  @JsonProperty("SkuCode")
  private String skuCode = null;

  @JsonProperty("Price")
  private Price price = null;

  @JsonProperty("CommissionApplied")
  private BigDecimal commissionApplied = null;

  @JsonProperty("StartedUtc")
  private Date startedUtc = null;

  @JsonProperty("CompletedUtc")
  private Date completedUtc = null;

  @JsonProperty("ProcessingState")
  private String processingState = null;

  @JsonProperty("ReceiptText")
  private String receiptText = null;

  @JsonProperty("ReceiptParams")
  private Map<String, String> receiptParams = null;

  @JsonProperty("AccountNumber")
  private String accountNumber = null;

  public TransferRecord transferId(TransferId transferId) {
    this.transferId = transferId;
    return this;
  }
}

Ниже приведен мой код, который я использовал для преобразования. Обратите внимание, что эти три куска кода будут служить одной и той же цели, и я попробовал их отдельно.

ObjectMapper mapper = new ObjectMapper();

//1 TransferRecord objTransRecord = mapper.readValue(result, TransferRecord.class);

//2 TransferRecord objTransRecord = mapper.readerWithView(TransferRecord.class).forType(TransferRecord.class).readValue(result);

//3 TransferRecord objTransRecord = mapper.readerFor(TransferRecord.class).readValue(result);

Проблема заключается в том, когда я пытаюсь создать объект,каждому значению присваивается значение ноль во всех трех подходах, даже если в строке имеются соответствующие данные.Может кто-нибудь указать, что я здесь делаю не так?

Заранее спасибо.:)

Ответы [ 3 ]

0 голосов
/ 01 февраля 2019

во-первых, json должен быть:

{
    "TransferId": {
      "TransferRef": "string",
      "DistributorRef": "string"
    },
    "SkuCode": "string",
    "Price": {
      "CustomerFee": 0,
      "DistributorFee": 0,
      "ReceiveValue": 0,
      "ReceiveCurrencyIso": "string",
      "ReceiveValueExcludingTax": 0,
      "TaxRate": 0,
      "TaxName": "string",
      "TaxCalculation": "string",
      "SendValue": 0,
      "SendCurrencyIso": "string"
    },
    "CommissionApplied": 0,
    "StartedUtc": "2019-01-31T10:10:20.527Z",
    "CompletedUtc": "2019-01-31T10:10:20.527Z",
    "ProcessingState": "string",
    "ReceiptText": "string",
    "ReceiptParams": {},
    "AccountNumber": "string"
  }

секунда, возможно, вам следует добавить методы получения и установки для каждого поля。

0 голосов
/ 01 февраля 2019

Используйте методы toString для прямой печати значений и структурирования ваших классов следующим образом

ObjectMapper mapper = new ObjectMapper();

        Data data = mapper.readValue(string, Data.class);

        System.out.println(data);

Класс данных

public class Data {
    @JsonProperty("TransferRecord")
    private TransferRecord transferRecord;

    @JsonProperty("ResultCode")
    private int
    resultCode;

    @JsonProperty("ErrorCodes")
    private List<ErrorCode> errorCodes;

    @Override
    public String toString() {
        return "Data [transferRecord=" + transferRecord + ", resultCode=" + resultCode + ", errorCodes=" + errorCodes
                + "]";
    }
}

Класс кода ошибки:

public class ErrorCode {
    @JsonProperty("Code")
    private String code;

    @JsonProperty("Context")
    private String context;

    @Override
    public String toString() {
        return "ErrorCode [code=" + code + ", context=" + context + "]";
    }
}

TransferRecordКласс:

public class TransferRecord {
    @JsonProperty("TransferId")
    private TransferId transferId;

    @JsonProperty("SkuCode")
    private String skuCode;

    @JsonProperty("Price")
    private Price price;

    @JsonProperty("CommissionApplied")
    private BigDecimal commissionApplied;

    @JsonProperty("StartedUtc")
    private Date startedUtc;

    @JsonProperty("CompletedUtc")
    private Date completedUtc;

    @JsonProperty("ProcessingState")
    private String processingState;

    @JsonProperty("ReceiptText")
    private String receiptText;

    @JsonProperty("ReceiptParams")
    private Map<String, String> receiptParams;

    @JsonProperty("AccountNumber")
    private String accountNumber;

    @Override
    public String toString() {
        return "TransferRecord [transferId=" + transferId + ", skuCode=" + skuCode + ", price=" + price
                + ", commissionApplied=" + commissionApplied + ", startedUtc=" + startedUtc + ", completedUtc="
                + completedUtc + ", processingState=" + processingState + ", receiptText=" + receiptText
                + ", receiptParams=" + receiptParams + ", accountNumber=" + accountNumber + "]";
    }
}

TransferId Класс:

public class TransferId {
    @JsonProperty("TransferRef")
    private String transferRef;

    @JsonProperty("DistributorRef")
    private String distributorRef;

    @Override
    public String toString() {
        return "TransferId [transferRef=" + transferRef + ", distributorRef=" + distributorRef + "]";
    }
}

Ценовой класс:

public class Price {
    @JsonProperty("CustomerFee")
    private int customerFee;

    @JsonProperty("DistributorFee")
    private int distributorFee;

    @JsonProperty("ReceiveValue")
    private int receiveValue;

    @JsonProperty("ReceiveCurrencyIso")
    private String receiveCurrencyIso;

    @JsonProperty("ReceiveValueExcludingTax")
    private int receiveValueExcludingTax;

    @JsonProperty("TaxRate")
    private int taxRate;

    @JsonProperty("TaxName")
    private String taxName;

    @JsonProperty("TaxCalculation")
    private String taxCalculation;

    @JsonProperty("SendValue")
    private int sendValue;

    @JsonProperty("SendCurrencyIso")
    private String sendCurrencyIso;

    @Override
    public String toString() {
        return "Price [customerFee=" + customerFee + ", distributorFee=" + distributorFee + ", receiveValue="
                + receiveValue + ", receiveCurrencyIso=" + receiveCurrencyIso + ", receiveValueExcludingTax="
                + receiveValueExcludingTax + ", taxRate=" + taxRate + ", taxName=" + taxName + ", taxCalculation="
                + taxCalculation + ", sendValue=" + sendValue + ", sendCurrencyIso=" + sendCurrencyIso + "]";
    }
}
0 голосов
/ 01 февраля 2019

Это НЕ класс TransferRecord.Ваш класс выборки json с 3 полями:

public class Something {
    @JsonProperty("TransferRecord")
    private TransferRecord transferRecord;
    @JsonProperty("ResultCode")
    private int resultCode;
    @JsonProperty("ErrorCodes")
    private List<ErrorCode> errorCodes;
}
...