I'm using StringBuffer to get JSON from a URL.
This is the original JSON
[{"name":"Italy","topLevelDomain":[".it"],"alpha2Code":"IT","alpha3Code":"ITA","callingCodes":["39"],"capital":"Rome","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","subregion":"Southern Europe","population":60665551,"latlng":[42.83333333,12.83333333],"demonym":"Italian","area":301336.0,"gini":36.0,"timezones":["UTC+01:00"],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"nativeName":"Italia","numericCode":"380","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"it","iso639_2":"ita","name":"Italian","nativeName":"Italiano"}],"translations":{"de":"Italien","es":"Italia","fr":"Italie","ja":"イタリア","it":"Italia","br":"Itália","pt":"Itália","nl":"Italië","hr":"Italija","fa":"ایتالیا"},"flag":"https://restcountries.eu/data/ita.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"ITA"}]
This is the JSON That I end up with once I convert it to a string from the response
[{"area":301336,"nativeName":"Italia","capital":"Rome","demonym":"Italian","flag":"https://restcountries.eu/data/ita.svg","alpha2Code":"IT","languages":[{"nativeName":"Italiano","iso639_2":"ita","name":"Italian","iso639_1":"it"}],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"subregion":"Southern Europe","callingCodes":["39"],"regionalBlocs":[{"otherNames":[],"acronym":"EU","name":"European Union","otherAcronyms":[]}],"gini":36,"population":60665551,"numericCode":"380","alpha3Code":"ITA","topLevelDomain":[".it"],"timezones":["UTC+01:00"],"cioc":"ITA","translations":{"br":"Itália","de":"Italien","pt":"Itália","ja":"イタリア","hr":"Italija","it":"Italia","fa":"ایتالیا","fr":"Italie","es":"Italia","nl":"Italië"},"name":"Italy","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","latlng":[42.83333333,12.83333333],"currencies":[{"symbol":"\u20ac","code":"EUR","name":"Euro"}]}]
This is my code for getting the JSON + Converting it.
JSONArray JSON = null;
//Reading Variables
BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input;
StringBuffer response = new StringBuffer();
//Adding response to StringBuffer
while((input = r.readLine()) != null) {
response.append(input);
}
//Stopping the reader
r.close();
System.out.println(response);
//Convert StringBuffer to JSON
JSON = new JSONArray(response.toString());
System.out.println(JSON);
return JSON;
Is there a way of preventing it from doing this?
It's not the StringBuffer but the JSONArray.
The order of elements in an array [] is maintained like the list ["AUT","FRA","SMR","SVN","CHE","VAT"] in both examples.
Anything as a name value pair surrounded by {} can be reordered like {"code":"EUR","name":"Euro","symbol":"€"} and {"symbol":"\u20ac","code":"EUR","name":"Euro"}.
To prevent this, you can keep it as a String or create your own object and define the toString method.
Your question is similar to Keep the order of the JSON keys during JSON conversion to CSV.
It is not StringBuffer doing this. It is the JSON implementation itself.
For a start, according to all of the JSON specifications that I have seen, the order of the attributes of a JSON object are not significant. A JSON parser is not expected to preserve the attribute order, and neither is the in memory representation of a JSON object. So, for example, a typical in-memory representation of a JSON object uses a HashMap to hold the attribute names and values.
So my first piece of advice to you would be to change your application so that the order of the JSON attributes doesn't matter. If you design a JSON API where attribute order matters, then your API will be problematic.
(If this is in a testcase, it is not difficult to compare JSON properly. For example, parse the JSON and compare objects attribute by attribute.)
If you are lumbered with a (so-called) JSON API where the order of attributes has some meaning, my advice is:
Complain. Submit a bug report. This is not a proper JSON API.
Look for a JSON library that provides a way to work around the bad design. For example, some libraries allow you to provide a Map class to be used when constructing a JSONObject. The default is usually HashMap, but you could use LinkedHashMap instead.
Problem:
I am unable to parse json request to an object containing double quotes in it.
For example:
jsonString = {
"desc":"Hello stackOverFlow, please reach on this email "asdas#gmail.com". thanks";
}
When I am trying to convert this I am not able parse to an variable, because it looks like invalid json but in real time the request has double quotes in it.
Please show me some good parsing techniques which can do parse this type of requests.
Thanks
You have to escape all of the double quotes, so for example:
String json = "\"{\"desc\":\"Hello stackOverFlow, please reach on this email \"asdas#gmail.com\". thanks\"}";
As you can see it is a lot of work to create very simple JSON, so you are better of using some library for that. I recommend you org.json, it is very lightweight and easy to use. Using it, it would look like this:
JSONObject json = new JSONObject();
json.put("description", "Your description....");
String jsonString = json.toString();
I have developed a tool that can test some requests to a server, the requests themselves are no more than some simple JSON files that are stored on the disc and can be added continuously, but ... there is one more thing, the JSON files contains an e-mail address that needs to be changed upon running the project each time, this is because each of users have a personal e-mail, I made that because server can't accept more than one request from an user. So I am looking for a solution to inject this e-mail address dynamically into JSON.
I'm using Java for this, and also jayway for REST API and Gson for JSONs. So far I looked into google, but can't find anything at all.
You could do this by these solutions:
Use json file as template string with markup like "{email: ${e-mail}}", then just use jsonTemplate.replace("${e-mail}", email[i])
parse json to Map or Object that model request, then change email field and build again json out of it
Use Gson.
Gson gson = new Gson();
String yourJsonInStringFormat = " {\"email\":placeHolder,\"password\":\"placeHolder\"}";
Map map = gson.fromJson(yourJsonInStringFormat, Map.class);
map.put("email", "jose#com.com");
map.put("password", "123456");
String newJson = gson.toJson(map);
System.out.println(newJson);
This prints out:
{"email":"jose#com.com","password":"123456"}
The fields being injected do not need to be there already. For example this also works:
Gson gson = new Gson();
String yourJsonInStringFormat = "{}";
Map map = gson.fromJson(yourJsonInStringFormat, Map.class);
map.put("email", "jose#com.com");
map.put("password", "123456");
String newJson = gson.toJson(map);
System.out.println(newJson);
I am developing a web-app using AJAX requests on the client-side and Servlets on the server-side.
My aim is to send objects of Javascript to server, then do some manipulations there and send it back to show here.
Let's say my js object is
var obj={hero:"Spiderman",name:"Peter Parker"};
My Approach
1.Convert obj to JSON string and send
var str= JSON.stringify(obj);
xmlhttp.open("POST",myurl,true);
xmlhttp.setRequestHeader("Content-Type","application/json",true);
xmlhttp.send("data="+str);
2. Recieve string,convert this back to JSON, manipulate "name" to "Bruce Wayne" and send it back as string
3.Recieve and convert back to Json
var data= JSON.parse(xmlhttp.responseText);
I am struggling at second point.I am using org.json for it .I searched and read docs but could not find satisfied answer for converting string to json and vica-versa in JAVA in my context.
It would be really helpful one could provide simple working code or point to some links where I can study.
P.S :
I cannot use Jquery as I am using AngularJS. See Why?
I will always send valid JSON string.
I can use other JSON lib. if its good than org.json and satisfy my needs.
Please provide its jar download link.
Assuming you are able to pull out data in your server code
This is how you can do it using org.json:
JSONParser parser = new JSONParser();
JSONObject requestObj = (JSONObject) parser.parse(data);
String name = (string)requestObj.get("name");
name = "Bruce Wayne";
Code to create the response can look something like this:
JSONObject response = new JSONObject();
response.put("name",name);
return response.toJSONString();
This assumes your server method returns a String type
And in case if you are using Servlet you can use HttpServletResponse object res to create response like:
res.setContentType("application/json");
OutputStream os = res.getOutputStream();
os.write(response.toString().getBytes());
os.close();
I have a couple of txt files that gets some information from android's (call,messages,etc) database and stores it as a Cursor object.
I then convert the Cursor onto a JSON object which is then stored on a txt file on an SD card on the device. When I read from the file I get lines as a String like this one:
{"date":1332969098495,"duration":0,"number":"7038673588","Device_ID":"streak"}
I have to store the values of the String onto a MySQL table. Is there a way that I can convert this back onto a JSON or maybe a Map?
I thought about editing the String so the values are surrounded by a single quote and use the MySQL syntax to simply load the fields on the file.
Thanks!
You can create a JSONObject from the string that you have. That will pretty much give the same functionality as that of java.util.Map. For e.g,
String jsonStr = "json representation of your data";
JSONObject jObj = new JSONObject(jsonStr);
jObj.get(yourKeyString);
//do more with your jObj here...
Hope this helps. Refer the JSONObject documentation for more details.
You need to use JSon-lib (or) GSon libraries for this purpose.
Example GSon code would be:
YourObject obj = gson.fromJson(inputJson, YourObject.class);
Note: YourObject is java class with getter/setter.
Here is an tutorial of using GSON library to achieve typed object conversion.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
Sathishpaul is correct but just to clarify :
JSONObject obj = new JSONObject(YourJSONString);
Long date = obj.getLong("date");
int duration = obj.getInt("duration");
etc..