-2

Hi I am trying to send a JSON object to the server. The JSON object is :

JSONObject j = new JSONObject("{'Hobbies':" + h + "}");

{"Hobbies" : "Programming & Gaming"}

But as I SEND this object via HTTP it gives me an error Unterminated Object at character 22. After a lot of research I found out the '&' splits the object. Is there anyway I can escape '&'. I tried '\&' but it doesn't work as there is no escape sequence like that.

Ishan Garg
  • 178
  • 2
  • 11

1 Answers1

1

Go to json.org and study the syntax carefully. A key or string value in JSON must be enclosed in double quotes. Your code is generating

{'Hobbies' : Programming & Gaming}

To do it the way you're doing it you need to escape the double quotes:

new JSONObject("{\"Hobbies\":\"" + h + "\"}");

However, it would be far better to construct a JSONObject out of separate key and value. I'm not sure which specific Java JSON package you're using, but for most this would be simply:

new JSONObject("Hobbies", h);
Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • This library is pretty bad and allows you to use the `String` literal `"{\"Hobbies\" : Programming & Gaming}"` as a JSON string. – Sotirios Delimanolis Aug 02 '14 at 21:26
  • @SotiriosDelimanolis - Yes, that's a valid string in JSON, but not valid JSON. It's just a string -- could just as well be "How now brown cow". – Hot Licks Aug 02 '14 at 21:29
  • I'm saying the parsing is very loose. It will not complain or fail given that value as its single constructor argument, although it is invalid JSON. – Sotirios Delimanolis Aug 02 '14 at 21:31
  • @SotiriosDelimanolis -- There are at least two different Java JSON packages that have the JSONObject class, so we don't know which is being used here. I would not trust one that treated `{"Hobbies" : Programming & Gaming}` as valid JSON, though. – Hot Licks Aug 02 '14 at 21:34
  • In any case, the parsing wouldn't fail at `&`. – Sotirios Delimanolis Aug 02 '14 at 21:36
  • @SotiriosDelimanolis so what do you use as a json library? I use `org.json` but I hear a lot about `GSON` and `Jackson` but Im not sure which one to use – meda Aug 02 '14 at 21:36
  • I've tried all `org.json` versions on [maven](http://mvnrepository.com/artifact/org.json/json) and they all pass at parsing the `String` value previously mentioned. – Sotirios Delimanolis Aug 02 '14 at 21:55
  • @HotLicks Yeah you were right I missed the quotes, the reason the '&' didn't work was without the quotes '&' was acting as a special character. – Ishan Garg Aug 02 '14 at 22:46