Getting java object back from JSON - java

I am putting some java objects in the Json at server side
like this :
ArrayList<VisjsNode>visjsNodes = new ArrayList<VisjsNode>();
ArrayList<VisjsConnection> visjsConnections = new ArrayList<VisjsConnection>();
String jsondata = null;
org.json.JSONObject object = new org.json.JSONObject();
try {
object.put("nodes", visjsNodes);
object.put("connections", visjsConnections);
jsondata = object.toString();
Now is there a way I can get these objects back from this json (jsondata) at client side
I am doing this:
com.google.gwt.json.client.JSONValue jsonValue = JSONParser.parseStrict(jsondata);
com.google.gwt.json.client.JSONObject jsonObject = jsonValue.isObject();
jsonValue = jsonObject.get("nodes");
Now I am trying this to get ArrayList back , by doing this
ArrayList<VisjsNode>visjsNodesFromjson = jsonValue ;
But its not compiling ,it says Incompatable types...
Can you please guide how we can retrieve the Java Object back from Json ..

That's because you're using two different JsonObject class. First you use the one which comes from org.json (org.json.JsonObject) and the other is com.google.gwt.json.client.JSONObject. Nevertheless, they're named similar, they're completely different classes.

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

Gson, creating a simple JsonArray of JsonObjects

I'm trying to build a JsonArray of JsonObjects using gson.
Each JsonObject will take the following format,
{"image":"name1"}
{"image":"name2"}
and so on.
I have a string array of the names ("name1","name2",...)
I cannot convert string array directly in to a JsonArray. I'm trying to create JsonObjects iteratively and add it to a JsonArray.
JsonObject innerObject;
JsonArray jArray = new JsonArray();
for(int i = 0; i<names.length; i++)
{
innerObject = new JsonObject();
innerObject.addProperty("image",names[i]);
jArray.add(innerObject);
}
But as I understand, add method in JsonArray takes a JsonElement and here I'm giving a JsonObject. I couldn't find a way to convert JsonObject to JsonElement.
The whole point of using gson will be gone when I do this. Is there a better way?
First, create a class that represents a single json object, e.g.:
class MyObject {
private String image;
public MyObject(String name) { image = name; }
}
Gson will use the class' variable names to determine what property names to use.
Then create an array or list of these using the data you have available, e.g.
ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));
Finally, to serialize to Json, do:
String json = new Gson().toJson(allItems);
And to get the data back from json to an array:
MyObject[] items = new Gson().fromJson(json, MyObject[].class);
For simple (de)serialization, there is no need to be dealing directly with Json classes.
If you are going to use GSON use it like this to convert to object
List<Image>images = new Gson().fromJson(json, Image[].class);
To get json string
String json = new Gson().toJson(images);
That's the point of gson you should not manipulate the data with loops and stuff. You need to take advantage of its powerful model parsing.
Maybe too late but... There is a way to do without creating a new class if you dont need it:
import com.google.gson.JsonObject;
import com.google.gson.JsonArray
...
...
JsonArray jobj = new JsonArray();
String[] names = new String[]{"name1","name2","name3"};
for(String name : names) {
JsonObject item = new JsonObject();
item.addProperty("name",name);
jobj.add(item);
}
System.out.println(jobj.toString());// ;)

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 parse internal JSON elements?

I'm using json-simple-1.1.1.jar which was referred by tutorialpoint.com.
My JSON file is shown here:
My java code is here:
I couldn't understand how I would access "onclick": "CloseDoc()" in my JSON file.
If I use the getObject method it is showing me an error:
The method getJSONObject(String) is undefined for the type JSONObject
onClick is inside the array menuitem which is inside the object menu , so you have to loop the array to retrieve what you want. You can try it like this:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new InputStreamReader(in));
String json_str = obj.toString();
JSONObject j_org_json_obj = new JSONObject(json_str);
JSONArray j_org_json_arr = j_org_json_obj.getJSONObject("menu").getJSONArray("menuitem");
for(int i=0;i<j_org_json_arr.length();i++)
{
System.out.println(j_org_json_arr.getJSONObject(i).getString("onClick()"));
}
Along with json-simple jar ,In the above code one more jar is included : org-json jar , so import that as well.
maybe you could check the import is org.json.simple.JSONObject
but this jar is not had a method call getJsonObject.

JAVA JSONObject parsing issue

I am using JSONObject to parse nested JSON from an API example:
{"results":[{"congress":"112","state":"NJ","num_results":"2","offset":"0","members": [{"id":"L000123","first_name":"Frank"..........................
I am having trouble accessing the members nested area using JSONObject.
This is my code, any thoughts?
url= new URL("http://api.nytimes.com/svc/politics/v3/us/legislative/congress/112/senate/members.json?&state=NJ&api-key=7967107ef3c9e8d6c2f560027f87904e:17:65990356");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(url.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse the JSON object returned
JSONObject jsonO = new JSONObject(urlContents);
System.out.println(jsonO.toString());
JSONObject results = jsonO.getJSONObject("results");
JSONObject senators = results.getJSONObject("members");
You should use third party library like GSON.
http://code.google.com/p/google-gson/

Categories