如何使用Java将动态Json转换为POJO类的特定格式

时间:2018-06-27 05:04:54

标签: java json java-ee jackson

输入Json文件类似于以下代码:

for x, y, txt in zip(x_lbl, y_lbl, lbl):
    plt.text(x, y, txt, va='center', ha='center')

预期输出(java类)

 {
      "Payload": {
        "any0": {
          "pricingResponse": {
            "priceDetails": {
              "priceDetails": {
                "seqId": "8015B000000Umo1QAC-",
                "companyCode": "EPA",
                "priceType": "Fuel Price",
                "priceRequestSource": ""
              },
              "priceLineItems": {
                "lineItem": [
                  {
                    "lineItemInfo": {
                      "seqId": "8015B000000Umo1QAC-28052018105047-022596",
                      "orderId": "00000266",
                      "lineItemId": "44",
                      "itemId": "70051",
                      "quantity": "100.00",
                      "unitPrice": "2.03200",
                      "unitPriceLCY": "2.03200"
                                   }
                    }
                            ]
                    }
                }
             }
           }
         }
      }

我试图使用杰克逊图书馆将其转换并作为单独的POJO类进行创建,但我想创建嵌套类。这是我的示例代码

 public class Payload 
   {
      public Any0 any0;
   }

    /* Stub Class for Any0 */
   public class Any0 
   {
        public PricingResponse pricingResponse;
   }

    /* Stub Class for PricingResponse */
    public class PricingResponse 
    {
        public PriceDetails priceDetails;
    }

    /* Stub Class for PriceDetails */
    public class PriceDetails 
    {
        public String seqId;
        public String priceRequestSource;
        public String companyCode;
        public String priceType;
        public String deliveryType;
        public String currencyCode;
        public String priceDate;
        public String applyOrderQuantity;
        public String totalOrderQuantity;
        public String customerId;
        public String shipToId;
        public String supplyLocationId;
        public String transporterId;
        public String onRun;
        public String orderId;
        public PriceDetails priceDetails;
        public PriceLineItems priceLineItems;
        public Error Error;
    }

    /* Stub Class for PriceLineItems */
    public class PriceLineItems 
    {
        public String orderId;
        public List<LineItem> lineItem;
    }

    /* Stub Class for LineItem */
    public class LineItem 
    {
        public LineItemInfo lineItemInfo;
        public AccountingDetails accountingDetails;
        public Error Error;
    }

这是我得到的输出 enter image description here

是否有可能将动态嵌套的Json类文件转换为Java类?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

对每个包含变量键和不变值(Map<String, ValueClass>类型)的结构使用ValueClass

如果您还想对具有可变值结构的地图进行反序列化,则需要编写一个自定义反序列化器,以推断应该将该JSON反序列化为哪个Java类。 Here's a tutorial for how can you do that with GSON