首页 > 解决方案 > 将字符串操作为 json 格式的 Java 代码

问题描述

String xtext = "#Samsung Electric Range with Fan Convection~86309930018~$525.00~TRUCK~0.0~R55856112#HAUL AWAY~07601000018~$24.99~TRUCK~0.0~R55856112#ELECTRIC RANGE C~88301170018~$21.99~TRUCK~0.0~R55856112";

需要示例将此字符串转换为 json 格式,如下所示。行的分隔符 # 和列的 ~ 具有相同的模式。注意:我需要将此代码插入到talend tjavarow组件中。提前欣赏。

{ "items":[{ "description":"Samsung Electric Range with Fan Convection",
             "id":"86309930018",
             "price": { "unitPrice":525.00 },
             "shipMethod":"TRUCK",
             "ivn":"R55856112",
             "quantity":0.0
           },
           { "description":"HAUL AWAY",
             "id":"07601000018",
             "price": { "unitPrice":24.99 },
             "shipMethod":"TRUCK",
             "ivn":"R55856112",
             "quantity":0.0
            },
            {
               "description":"ELECTRIC RANGE C",
               "id":"88301170018",
               "price": { "unitPrice":21.99 },
               "shipMethod":"TRUCK",
               "ivn":"R55856112",
               "quantity":0.0
            }
          ]
}

收到...

String str = "Samsung Electric Range with Fan Convection~86309930018~$525.00~TRUCK~0.0~R55856112#HAUL AWAY~07601000018~$24.99~TRUCK~0.0~R55856112#ELECTRIC RANGE C~88301170018~$21.99~TRUCK~0.0~R55856112";

String[] aStr;
String[] bStr;
String desc;
String id;
String price;
String shipMethod;
String ivn;
String quantity;

aStr = str.split("#");

for (String a : aStr ) 
 {
   System.out.println(a);
   
   bStr = a.split("~");  
   desc = bStr[0];
   id = bStr[1];
   price = bStr[2];
   shipMethod = bStr[3];
   ivn = bStr[4];
   quantity = bStr[5];
   
   System.out.println(desc+"|"+id+"|"+price+"|"+shipMethod+"|"+ivn+"|"+quantity);
   
   
 }

标签: javajson

解决方案


你需要把字符串切成数组

String [ ] split ( String regex, int limit )

首先拉出#和~之间的字符串,取出剩余的字符串并使用“~”作为分隔符将其拆分

id = array[0]
price = array[1]
shipMethod = array[2]
ivn = array[3]
quantity = array[4]

然后你可以把它全部打包成json


推荐阅读