简体   繁体   中英

escaping quotes in java json

I'm preparing JSON and some part I do with

ls += "{ \"id\": \"" + list.indexOf(el) + "\", \"cell\" : [\"" +  el.toString() + "\"]}," ;

but when I check in Firebug what is sent I see that backslahes are not removed:

{"total":"1","page":"1","records":"1","rows":"[{ \"id\": \"0\", \"cell\" : [\"data1\"]},{ \"id\": \"1\", \"cell\" : [\"data2\"]}]"}

any ideas? I tried with ls.replaceAll("\\\\\\\\", " "); but it doesn't work

What JSON library are you using? It looks to me like you're correctly building strings like

{ "id": "0", "cell" : ["data1"]}

but then inserting them as strings into some structure that is serialized by a JSON library. The JSON serializer then has to re-escape the quotes to make the result into a valid JSON string literal.

Edit: you say you're using Gson, so I presume you have a top level class you're serializing which currently has a String rows property which you're filling with a JSON string. Instead you need to create a new class to represent one row

class Row {
  private String id;
  private List<String> cell;
  // constructor, getters and setters as usual
}

And change the rows property to be a List<Row> . Now rather than concatenating strings together to build the JSON yourself you simply populate your top-level object with the appropriate Row objects and let Gson handle converting them to JSON.

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