简体   繁体   中英

Remove quotes from json array

I have the following problem:

I have an ArrayList in Java.

I convert the ArrayList to string like this:

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. 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 arr=[{"status":"ERROR","position":"[48.2748206,8.849529799999999]"}];

Then you can take out JSONObject like this:

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 :

    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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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