我有一个管道分隔文件,其中包含不同的分隔符,如下所示,
c_prd_id||13043|L|
c_prd_cd||c13043|L|
c_title||14k Gold Two Tone Sparkle Chain Necklace|L|
c_alt_tag||14k Gold Two Tone Sparkle Chain Necklace|L|
c_desc||Add a little dazzle</strong> to your wardrobe with this two-tone gold chain.|L|
c_web_tmp||collectionBTemplate|L|
c_val_icons||Online_Exclusive.gif|L|
c_r_cnt||2|L|
c_r_val||5|L|
c_child_prd||281506|L|
c_child_prd||281527|L|
c_child_prd||281544|L|
c_prc_dsply_cd||REG|L|
c_create_dt||1340214009|L|
c_inv||0|L|
c_primary_type||Jewelry|L|
c_prd_type||Necklaces|L|
c_prd_subtype||Necklaces|L|
|R||L|
c_prd_id||13045|L|
c_prd_cd||c13045|L|
c_title||14k Gold Two-Tone Singapore Chain Necklace|L|
c_alt_tag||14k Gold Two-Tone Singapore Chain Necklace|L|
c_desc||Glamorous!Enhance your jewelry collection with this delicate 14k yellow gold and 14k white gold Singapore chain.|L|
c_web_tmp||collectionBTemplate|L|
c_val_icons||Online_Exclusive.gif|L|
c_r_cnt||1|L|
c_r_val||5|L|
c_child_prd||281507|L|
c_child_prd||281528|L|
c_child_prd||281545|L|
c_prc_dsply_cd||REG|L|
c_create_dt||1340214010|L|
c_inv||0|L|
c_primary_type||Jewelry|L|
c_prd_type||Necklaces|L|
c_prd_subtype||Necklaces|L|
|R||L|
我需要将这些分隔的数据转换为JSON格式。请建议。
答案 0 :(得分:1)
您可以通过一些拆分和替换操作来执行此操作。以下是Java中的内容示例,您可以将其转换为调用toJsonArr
方法的json格式。
public static String toJsonArr(String src){
StringBuilder builder = new StringBuilder();
String objArray[] = src.split("\\|R\\|\\|L\\|");
builder.append("[");
for(String obj : objArray){
builder.append(toJsonObj(obj)).append(",");
}
//remove last comma ,
String str = builder.substring(0, builder.length()-1);
return str+"]";
}
public static String toJsonObj(String src){
StringBuilder builder = new StringBuilder();
String elemArray[] = src.split("\\|L\\|");
builder.append("{");
for(String elem : elemArray){
//for empty lines
if(elem.trim().length()!=0)
builder.append(toJsonElem(elem)).append(",");
}
//remove last comma ,
String str = builder.substring(0, builder.length()-1);
return str+"}";
}
public static String toJsonElem(String src){
StringBuilder builder = new StringBuilder();
builder.append("\"").append(src.trim().replaceAll("\\|\\|", "\":\"")).append("\"");
return builder.toString();
}