java - 将字符串操作为 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);
}
解决方案
你需要把字符串切成数组
String [ ] split ( String regex, int limit )
首先拉出#和~之间的字符串,取出剩余的字符串并使用“~”作为分隔符将其拆分
id = array[0]
price = array[1]
shipMethod = array[2]
ivn = array[3]
quantity = array[4]
然后你可以把它全部打包成json
推荐阅读
- regex - 如何通过删除postgres中的中间部分来获取字符串
- python-3.x - 循环中打印位置导致的差异
- scala - Spark Scala 中的点积
- mysql - 如何在mysql中找到平均差异?
- sql - 如果我的要求是 postgresql 和 sql server,如何使 spring boot 代码通用或动态?
- c# - Lamda 表达式不适用于 String.Count()
- python - 在矩形matplotlib内绘制线宽
- git - 如何在 Google Colab 中的 GitHub 分支之间切换
- azure - 如何将与 VNet 集成的 azure 函数应用程序列入 Even Grid 订阅白名单
- python - 机器学习模型过拟合