java string to json conversion using json lib - java

Issue here that while converting to json object decimal value get truncated. I'm using Json-lib for below code.
String str = "{'key':'key','type':'string','value':9276658.1}";
JSONObject fromObject = JSONObject.fromObject(str);
// sysout -> output {"key":"key","type":"string","value":9276658}
How to fix this?

Related

Android: gson.toJson converter giving empty string for Android objects

I'm trying to covert Java object to json using Gson library, but its not working as expected and returning empty string,
my code:
String ie = new String("Jack");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
it returns:
{}
Please let me know if anything wrong with library, I tried with other Objects as well all returning null value like for Intent Object, ApplicationInfo etc
If you want convert string to json object, your string must be json as well.
For example:
String ie = new String("{\"name\": \"Jack\"}");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);

How can I encode JSON object content into a JSON string?

Trying to find a way to stringify a JSON string, with escape characters like JavaScript.
For example --
Input:
{"name":"Error","message":"hello"}
Output:
"{\"name\":\"Error\",\"message\":\"hello\"}"
I am able to get the object as JSON String using Gson, but not stringify (with escape characters).
Is this possible with Java?
Your input is a JSON object as text, presumably stored in a String. You're essentially trying to convert that text to a JSON string. So do just that.
String input = "{\"name\":\"Error\",\"message\":\"hello\"}";
System.out.println("Original JSON content: " + input);
Gson gson = new Gson();
String jsonified = gson.toJson(input);
System.out.println("JSONified: " + jsonified);
Since quotes (and other characters) must be escaped in JSON strings, the toJson will properly perform that transformation.
The code above will produce the
Original JSON content: {"name":"Error","message":"hello"}
JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"
In other words, jsonified now contains the content of a JSON string.
With Jackson, the process is the same, just serialize the String instance that contains your JSON object text
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, input);
jsonified = writer.toString();
System.out.println("JSONified: " + jsonified);
produces
JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"
Another solution, I noted in comments:
Jackson's JsonStringEncoder.quoteAsString() Example: stackoverflow.com/a/40430760/639107
You can try this on your output json string :
String strWithEscChar = output.replaceAll("\"", "\\\\\"");

How to decode JSON file created with GSON in Java?

I've successfully created a JSON file with gson but now that I want to parse that same file, the encoding gets all messed up.
This is the code I use to read the JSON file:
BufferedReader jsonFile = new BufferedReader(new FileReader("file.json"));
Map<String, List<long[]>> trafficInput = new HashMap<>();
trafficInput = gson.fromJson(jsonFile, HashMap.class);
I can't seem to figure out how to ensure the file gets parsed the right way.
For instance, this valid JSON code from the file:
{"paris":[[1485907200000,182184411,41274],[1485993600000,151646118,36697],"london":[[1485907200000,30200160,155827]}
...gets parsed like this:
{"paris":[[1.4859072E12,1.82184411E8,41274.0],[1.4859936E12,1.51646118E8,36697.0],"london":[[1.4859072E12,3.020016E7,155827.0]}
This messes up the rest of the code as the longs aren't longs anymore.
For instance, if I try to print out a value, like so:
System.out.println(trafficInput.get("paris").get(0)[0]);
... I get this error:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [J
Any help?
This is happening because of the following line:
trafficInput = gson.fromJson(jsonFile, HashMap.class);
This line instructs gson to deserialize the string into HashMap without specifying any type, and hence, gson applies its default conversion mechanism (i.e. converting Number into double etc). This is why Sysout statement results in a ClassCastException because that element is not an array.
All you need to do is to specify a TypeToken while calling fromJson method and it will take care of types. e.g.:
Gson gson = new Gson();
Type type = new TypeToken<Map<String, List<long[]>>>(){}.getType();
Map<String, List<long[]>> trafficInput = new HashMap<>();
trafficInput = gson.fromJson("{\"paris\":[[1485907200000,182184411,41274],[1485993600000,151646118,36697]],\"london\":[[1485907200000,30200160,155827]]}", type);
System.out.println(trafficInput);
System.out.println(gson.toJson(trafficInput));
The above snippet prints numbers without scientific notation.

way to parse my json in java

I want to parse my json string at run time. But, the problem is my json string is not a valid one due to some issues. Is there any way to parse the json with validation. My json string looks like this:
{"page_1":"{\"city\":\"Delhi\",\"locality\":\"Alaknanda\",\"Name_of_Person\":\"Varun Patil\",\"User_email_address\":\"varun.vap#gmail.com\",\"user_phone_number\":\"\",\"sub_locality\":\"\",\"street_name\":\"Pune\",\"home_plot_no\":\"xyz\",\"pin_code\":\"411060\",\"project_society_build_name\":\"\",\"landmark_reference_1\":\"\",\"landmark_reference_2\":\"\",\"No_of_Schools\":20,\"No_of_Hospitals\":20,\"No_of_Metro\":0,\"No_of_Mall\":20,\"No_of_Park\":20,\"Distance_of_schools\":1.51,\"Distance_of_Hospitals\":2.5,\"Distance_of_Metro\":0,\"Distance_of_Mall\":1.9,\"Distance_of_Park\":1.1,\"lat\":28.5304408,\"lng\":77.2505733,\"ipinfo\":{\"ip\":\"59.88.97.45\",\"hostname\":\"No Hostname\",\"city\":\"Pune\",\"region\":\"Maharashtra\",\"country\":\"IN\",\"loc\":\"18.5333,73.8667\",\"org\":\"AS9829 National Internet Backbone\",\"postal\":\"411001\"}}","page_2":"{\"home_type\":\"Flat\",\"area\":\"1000\",\"beds\":\"2 BHK\",\"bath_rooms\":2,\"building_age\":\"3\",\"floors\":\"\",\"balcony\":1,\"amenities\":\"regular\",\"amenities_options\":{\"gated_security\":\"\",\"physical_security\":\"\",\"cctv_camera\":\"\",\"controll_access\":\"\",\"elevator\":\"\",\"power_back_up\":\"\",\"parking\":\"\",\"partial_parking\":\"\",\"onsite_maintenance_store\":\"\",\"open_garden\":\"\",\"party_lawn\":\"\",\"amenities_balcony\":\"\",\"club_house\":\"\",\"fitness_center\":\"\",\"swimming_pool\":\"\",\"party_hall\":\"\",\"tennis_court\":\"\",\"basket_ball_court\":\"\",\"squash_coutry\":\"\",\"amphi_theatre\":\"\",\"business_center\":\"\",\"jogging_track\":\"\",\"convinience_store\":\"\",\"guest_rooms\":\"\"},\"interior\":\"regular\",\"interior_options\":{\"tiles\":\"\",\"marble\":\"\",\"wooden\":\"\",\"modular_kitchen\":\"\",\"partial_modular_kitchen\":\"\",\"gas_pipe\":\"\",\"intercom_system\":\"\",\"air_conditioning\":\"\",\"partial_air_conditioning\":\"\",\"wardrobe\":\"\",\"sanitation_fixtures\":\"\",\"false_ceiling\":\"\",\"partial_false_ceiling\":\"\",\"recessed_lighting\":\"\"},\"location\":\"regular\",\"location_options\":{\"good_view\":\"\",\"transporation_hub\":\"\",\"shopping_center\":\"\",\"hospital\":\"\",\"school\":\"\",\"ample_parking\":\"\",\"park\":\"\",\"temple\":\"\",\"bank\":\"\",\"less_congestion\":\"\",\"less_pollution\":\"\"},\"maintenance\":\"\",\"maintenance_value\":\"\",\"near_by\":{\"school\":\"\",\"hospital\":\"\",\"mall\":\"\",\"park\":\"\",\"metro\":\"\"},\"city\":\"Delhi\",\"locality\":\"Alaknanda\",\"token\":\"9a2a8bf359494054f98c80009b5bd0e7\"}"}
I tried the following methods:
String result = java.net.URLDecoder.decode(jsonstring, "UTF-8");
String withCharacters = StringEscapeUtils.unescapeHtml(jsonstring);
JSONObject json = (JSONObject)new JSONParser().parse(jsonstring);
System.out.println("city=" + json.get("city"));
System.out.println("locality=" + json.get("locality"));
Nothing works for me and any help will be appreciated.
You have some escaped json inside your main json structure. That means it's valid json, but after parsing the main structure you have to parse the value of page_1 (and probably all remaining pages as well). Try this:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonstring);
JSONObject nestedJson = (JSONObject)parser.parse(json.get("page_1"));
System.out.println("city=" + nestedJson.get("city"));

how to covert json string to byte array in java

String json="{"FROM_JID":"6bc24cac4eaf304ce1731bd5aebe9b0419052701","TO_JID":"dfc8d53f402373a1d3622dde50e180b388b36bc1","TYPE_ID":"1","PLATFORM":"IOS","CONTENT":"{\"FROM_JID\":\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\",\"FROM_HOST\":\"ssdevim.mtouche-mobile.com\",\"FROM_JNAME\":\"test1\",\"TO_JID\":\"dfc8d53f402373a1d3622dde50e180b388b36bc1\",\"TO_HOST\":\"ssdevim.mtouche-mobile.com\",\"MESSAGE_ID\":\"LiYaU-39\",\"MESSAGE_TYPE\":\"enc\",\"MESSAGE\":\"test1 has sent you an encrypted message.\",\"STAMP\":\"2015-11-12 12:04:54.252241\",\"BADGE\":3,\"CONTENT-AVAILABLE\":1,\"SOUND\":\"dafault\"}","DEVICE_ID":"AC53D4F0-DAAA-475E-9668-5E9E7485797C","PUSH_ID":"c9544c8db2117f02f3edc8af9058b3d54c15500302bf6f47c487193876f6dc23","CREATE_DATE":"2015-11-12","CREATE_TIME":"04:04:54"}";
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
but it showing error
First, this won't compile:
String json="{"FROM_JID":"6bc24cac4eaf304ce1731bd5aebe9b0419052701","TO_JID":"dfc8d53f402373a1d3622dde50e180b388b36bc1","TYPE_ID":"1","PLATFORM":"IOS","CONTENT":"{\"FROM_JID\":\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\",\"FROM_HOST\":\"ssdevim.mtouche-mobile.com\",\"FROM_JNAME\":\"test1\",\"TO_JID\":\"dfc8d53f402373a1d3622dde50e180b388b36bc1\",\"TO_HOST\":\"ssdevim.mtouche-mobile.com\",\"MESSAGE_ID\":\"LiYaU-39\",\"MESSAGE_TYPE\":\"enc\",\"MESSAGE\":\"test1 has sent you an encrypted message.\",\"STAMP\":\"2015-11-12 12:04:54.252241\",\"BADGE\":3,\"CONTENT-AVAILABLE\":1,\"SOUND\":\"dafault\"}","DEVICE_ID":"AC53D4F0-DAAA-475E-9668-5E9E7485797C","PUSH_ID":"c9544c8db2117f02f3edc8af9058b3d54c15500302bf6f47c487193876f6dc23","CREATE_DATE":"2015-11-12","CREATE_TIME":"04:04:54"}";
You even can notice that its syntax is not highlighted properly.
You need to escape your quotes in order to make Java recognize it as a part of a string, but not your code:
String json="{\"FROM_JID\":\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\",\"TO_JID\":\"dfc8d53f402373a1d3622dde50e180b388b36bc1\",\"TYPE_ID\":\"1\",\"PLATFORM\":\"IOS\",\"CONTENT\":\"{\\\"FROM_JID\\\":\\\"6bc24cac4eaf304ce1731bd5aebe9b0419052701\\\",\\\"FROM_HOST\\\":\\\"ssdevim.mtouche-mobile.com\\\",\\\"FROM_JNAME\\\":\\\"test1\\\",\\\"TO_JID\\\":\\\"dfc8d53f402373a1d3622dde50e180b388b36bc1\\\",\\\"TO_HOST\\\":\\\"ssdevim.mtouche-mobile.com\\\",\\\"MESSAGE_ID\\\":\\\"LiYaU-39\\\",\\\"MESSAGE_TYPE\\\":\\\"enc\\\",\\\"MESSAGE\\\":\\\"test1 has sent you an encrypted message.\\\",\\\"STAMP\\\":\\\"2015-11-12 12:04:54.252241\\\",\\\"BADGE\\\":3,\\\"CONTENT-AVAILABLE\\\":1,\\\"SOUND\\\":\\\"dafault\\\"}\",\"DEVICE_ID\":\"AC53D4F0-DAAA-475E-9668-5E9E7485797C\",\"PUSH_ID\":\"c9544c8db2117f02f3edc8af9058b3d54c15500302bf6f47c487193876f6dc23\",\"CREATE_DATE\":\"2015-11-12\",\"CREATE_TIME\":\"04:04:54\"}";
Second, if you already have a String and you want to convert it to byte[], why do you deserialize it? Just convert it to byte array:
byte[] bytes = json.getBytes();

Categories