PMe
PMe

Reputation: 565

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

Upvotes: 1

Views: 5284

Answers (3)

McDowell
McDowell

Reputation: 108969

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

Upvotes: 0

Braj
Braj

Reputation: 46871

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

Upvotes: 4

nsthethunderbolt
nsthethunderbolt

Reputation: 2095

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

}

Upvotes: 0

Related Questions