简体   繁体   English

从json数组中删除引号

[英]Remove quotes from json array

I have the following problem: 我有以下问题:

I have an ArrayList in Java. 我在Java中有一个ArrayList。

I convert the ArrayList to string like this: 我将ArrayList转换为这样的字符串:

Gson gson = new Gson();
String feeds += gson.toJson(arrayList);

This is the result: 结果如下:

[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}]

But i need the following output: 但我需要以下输出:

[{"status":"ERROR","position": [48.2748206,8.849529799999999]}]

The Value of position should be without quotes. 头寸价值不应带引号。 How can i realize that? 我怎么能意识到呢?

Many thanks in advance 提前谢谢了

Greets 招呼

Replace the double quotes around position's value using String#replaceAll() method. 使用String#replaceAll()方法替换位置值周围的双引号。 Just create a regex and replace double quotes with empty sting. 只需创建一个正则表达式并用空字符串替换双引号即可。

Try with Positive Lookbehind and Positive Lookahead. 尝试使用正向后向和正向前向。

sample code: 样例代码:

String json = "[{\"status\":\"ERROR\",\"position\":\"[48.2748206,8.849529799999999]\"}]";
String regex = "(?<=\"position\":)\"|\"(?=\\}\\])";
System.out.println(json.replaceAll(regex, ""));

Here is DEMO 这是演示


Try with grouping and substitutions as well. 也尝试分组和替换。

sample code: 样例代码:

String json = "[{\"status\":\"ERROR\",\"position\":\"[48.2748206,8.849529799999999]\"}]";
String regex = "(\"position\":)\"([^\"]*)\"";
System.out.println(json.replaceAll(regex, "$1$2"));

Here is DEMO 这是演示

I don't think you should go like this, may be you should change your work structure, But if you do want to typecast manually, then you can do it this way. 我认为您不应该这样,也许您应该更改工作结构,但是如果您想手动键入内容,则可以这样做。 Suppose you have a JSONArray object like this: 假设您有一个类似JSONArray的对象:

JSONArray arr=[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}];

Then you can take out JSONObject like this: 然后,您可以像这样取出JSONObject:

Iterator iterator = array.iterator();

while(iterator.hasNext()){
    Gson gson = new Gson();
    ClassToCastInto obj = gson.fromJson((JsonElement)iterator.next();, ClassToCastInto.class);
    System.out.println(obj.someProperty);

}

Consider using a Gson JsonWriter : 考虑使用Gson JsonWriter

    StringWriter buffer = new StringWriter();
    JsonWriter writer = new JsonWriter(buffer);
    writer.beginArray().beginObject();
    writer.name("status").value("ERROR");
    writer.name("position").beginArray();
    for (double value : Arrays.asList(48.2748206, 8.849529799999999)) {
        writer.value(value);
    }
    writer.endArray().endObject().endArray().close();
    String json = buffer.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM