如何在不使用replace方法的情况下从列表中删除逗号

时间:2016-03-18 13:53:11

标签: java json

我的情况是我的原始数据有逗号。 实际上,数据是JSON对象,其中包含一些逗号

我正在通过BufferedReader读取包含我的JSON对象的文件 现在BufferedReader输出我在列表中添加。

一切正常但请求失败,因为.toString();也添加了额外的列表逗号

String sCurrentLine = null;
BufferedReader br = new BufferedReader(new FileReader("/home/shubham/git/productApi"));
ArrayList<String> list = new ArrayList<String>();

while ((sCurrentLine = br.readLine()) != null) {
    System.out.println(sCurrentLine);
    list.add(sCurrentLine);
}

request.payload = list.toString();
System.out.println("dd =" + request.payload);

我的JSON

{
    "products":
    {
        "productsApp11": {
            "code": "productsApp11",
            "name": "productsApp11",
            "attribute_set": "one",
            "product_type": "product",
            "status": "active"
            }
    }
}

但是因为.toString数据如下所示: -

[{,
    "products": ,
    {,
        "productsApp11": {,
            "code": "productsApp11",
            ,
            "name": "productsApp11",
            ,
            "attribute_set": "Apparel",
            ,
            "product_type": "product",
            ,
            "status": "active",
        },
    },
}]

任何解决方案都将不胜感激

1 个答案:

答案 0 :(得分:2)

您需要使用行分隔符加入列表。 toString()的dafault List用逗号分隔项目。

Java 8

String sCurrentLine = null;
BufferedReader br = new BufferedReader(new FileReader("/home/shubham/git/productApi"));
ArrayList<String> list = new ArrayList<String>();

while ((sCurrentLine = br.readLine()) != null) {
    list.add(sCurrentLine);
}

br.close();

request.payload = String.join(System.getProperty("line.separator"), list);
System.out.println("dd =" + request.payload);

番石榴

Joiner.on(System.getProperty("line.separator")).join(list);

Java 7

String payload = join(System.getProperty("line.separator"), list);
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) {
    StringBuffer buff = new StringBuffer();

    if (elements != null) {
        Iterator<?> it = elements.iterator();

        if (it.hasNext()) {
            buff.append(it.next());
        }

        while (it.hasNext()) {
            buff.append(delimiter).append(it.next());
        }
    }

    return buff.toString();
}