如何在JSON值中解析escape characteres?

时间:2017-03-16 18:04:15

标签: java json csv

我正在尝试创建一个JSONParser,它将JSON密钥和值从两个JSON文件(一个用英语,一个用葡萄牙语)转换为CSV。

但是,生成CSV时,转义字符仍会显示在文本中。我正在使用Oracle的JSONP。如何解析转义字符?我必须使用其他图书馆吗?

示例

key:“validation.msg.calendar.repeating.cannot.be.blank”: value(inPortuguese):“\”Repetindo \“nãopodeser em布朗库“。,

CSV文件的输出为: \“Repetindo \”nãopodeser em branco。

库没有为“。”解析转义。 谢谢!

public class JSONParser {
    private String DELIMITER=",";
    private StringBuilder sb = new StringBuilder("Termo"+DELIMITER+"Inglês"+DELIMITER+"Português\r\n");
    private Writer wrt;
    private JsonObject obj1, obj2;
    private HashMap<String, String> hm1, hm2;
    private Iterator<String> it1, it2;

    public JSONParser(InputStream fis, InputStream fis2) {
        obj1 = readJson(fis);
        obj2 = readJson(fis2);
        it1 = getIterator(obj1.keySet());
        it2 = getIterator(obj2.keySet());
        hm1 = createHashMap(obj1, it1);
        hm2 = createHashMap(obj2, it2);

    }

    public HashMap<String, String> createHashMap(JsonObject obj, Iterator<String> it) {
        HashMap<String, String> hm = new HashMap<String, String>();
        while (it.hasNext()) {
            String key = it.next();
            hm.put(key, obj.get(key).toString());
        }
        return hm;

    }

    public JsonObject readJson(InputStream fis) {
        JsonReader reader = Json.createReader(fis);
        JsonObject obj = reader.readObject();
        reader.close();
        return obj;

    }

    public Iterator<String> getIterator(Set<String> keys) {
        Iterator<String> it = keys.iterator();
        return it;
    }

    public void generateCSV(String filename) throws IOException {
        wrt = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "ISO-8859-1"));
        Set<String> keys = obj1.keySet();
        Iterator<String> it = keys.iterator();

        while (it.hasNext()) {
            String key = it.next();
            if(key.startsWith("#")) continue;
            String pt = "";
            if (hm2.get(key) != null)
                pt = hm2.get(key).toString();
            sb.append("\""+key+"\"" + DELIMITER + hm1.get(key).toString() + DELIMITER + pt +"\r\n");
        }   
        wrt.write(sb.toString());
        wrt.close();
    }
}

1 个答案:

答案 0 :(得分:0)

你的问题很可能在这里:

hm1.get(key).toString()

如果这是我们正在讨论的JsonValue.toString,那么问题在于它被覆盖以返回JSON字符串,而不是已解析的值。

JsonObject的文档建议使用

  

在上面的示例2中,“John”可以使用

     

String firstName = object.getString("firstName");