I have recently started doing Android development, I am using Parse.com and native Java for building the app. What I am trying to do is figure out how to create objects that are created from the JSON result via a callback from Parse Parse.com.
{
"result":
{
"count": 3,
"lang": "en-US",
"tasks": [
{
"ID": "0123",
"Name": "Task 1",
"AssingedTo": "Darxval",
"Scope": "Home"
},
{
"ID": "0124",
"Name": "Task 2",
"AssingedTo": "Darxval",
"Scope": "Home"
},
{
"ID": "0125",
"Name": "Task 3",
"AssingedTo": "Darxval",
"Scope": "Home"
}
]
}
}
The method I call via Parse is shown below.
(see documentation for more info on the method here):Parse Documentation
ParseCloud.callFunctionInBackground("RetrieveTasks", new HashMap<String, Object>(), new FunctionCallback<Object>() {
void done(Object result, ParseException e) {
if (e == null) {
// do stuff with object
}
}
});
I have tried to change the Function callback to a class that takes in the json described as a bunch of strings and a ListArray of Task objects. But it does not create the object. It always want to use HashMap. Is there a way to turn the data into the object I want instead of a HashMap? Is there a interface I need to "implement" on my objects to allow the creation of the object on callback?
Any help in this would be greatly appreciated.
What object is added to the HashMap? Is it a JSONObject?
If so, you can convert a JSONObject to whatever custom object you are looking for using a constructor, and the data from the JSONObject.
For example, if your JSONObject that is returned is called "output":
try {
JSONObject result = output.getJSONObject("result");
int count = result.getInt("count");
String lang = result.getString("lang");
JSONArray tasks = result.getJSONArray("tasks");
JSONObject firstObjectInArray = tasks.getJSONObject(0);
String firstID = firstObjectInArray.getString("ID");
} catch (JSONException e) {
e.printStackTrace();
}
etc.
Then use your constructor for your Object to create a new object:
Object obj = new Object(count, lang, firstID);
etc.
For more information
Related
I am trying to automate one API using rest API JAVA. I have kept sample request json in one file and before passing that json I want to modify some values. New values are in Map.
For example I want to modify 'company' value to 'Microsoft'(which is in hashmap newInputs). Problem is my code is adding new 'company' at the top of body instead of updating it. How do i update specific values in Items array.
json body in file
{
"Items": [
{
"newValue": "Q3",
"company": "Test",
"oldValue": "Q2",
"Date": "2022-03-27"
}
]
}
What i want to pass to API
{
"Items": [
{
"newValue": "Q3",
"company": "Microsoft",
"oldValue": "Q2",
"Date": "2022-03-27"
}
]
}
What my code is passing
{
"company": "Microsoft",
"Items": [
{
"newValue": "Q3",
"company": "Test",
"oldValue": "Q2",
"Date": "2022-03-27"
}
]
}
My code
public static String createItem(Map<String, String> newInputs) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
jsonArray = new JSONArray(new String(
Files.readAllBytes(Paths.get("src", "test", "resources", "Payloads", "testdata.json"))));
jsonObject = new JSONObject(jsonArray.get(0).toString());
for (String key : newInputs.keySet()) {
jsonObject.put(key, newInputs.get(key));
}
jsonArray.put(0, jsonObject);
}
I am trying to extract title, videoId, and description data of all the videos I got from using YT Data API. I was able to return the data in what looks like JSON format (but it is actually LinkedHashMap when I check with getClass()) in Postman and Chrome browser, but was unable to extract the value from specific keys I have mentioned above.
I tried:
System.out.println((rest.getForObject(url, Object.class, params)).get("items"));
It asks me to cast to JSONObject
Overall, I need to extract the data and convert into xml before sending it over to ActiveMQ
Edit:
Format I get in Postman/Chrome browser
{
"kind": "youtube#searchListResponse",
"etag": "3LV4enCWAzOaiqJb_cMIUVklXJY",
"nextPageToken": "CAUQAA",
"regionCode": "CA",
"pageInfo": {
"totalResults": 478712,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "gt6x7J2XpzU8Mpb3yv9_HmNTzWY",
"id": {
"kind": "youtube#video",
"videoId": "I_ZK0t9-llo"
},
"snippet": {
"publishedAt": "2021-03-01T18:15:13Z",
"channelId": "UC2WHjPDvbE6O328n17ZGcfg",
"title": "Stack Overflow is full of idiots.",
"description": "The Stack Overflow culture needs to be fixed. The overall gatekeeping & elitism in computer science & programming - as a whole ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/I_ZK0t9-llo/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/I_ZK0t9-llo/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/I_ZK0t9-llo/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "ForrestKnight",
"liveBroadcastContent": "none",
"publishTime": "2021-03-01T18:15:13Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "RwmGP1qMzUCzK6oV82s0NUEOETw",
"id": {
"kind": "youtube#video",
"videoId": "sMIslcynm0Q"
},
"snippet": {
"publishedAt": "2021-03-07T16:00:13Z",
"channelId": "UCXwjZTvpFiBl93ACCUh1NXQ",
"title": "How To Use Stack Overflow (no, ForrestKnight, it's not full of idiots)",
"description": "Hey everyone, I can't believe I have to make this video. Unfortunately ForrestKnight recently made a video saying Stack Overflow ...",
"thumbnails": {
...
Edit2: I tried
JSONObject jsonObject = new JSONObject( rest.getForObject(url, Object.class, params));
JSONArray array = jsonObject.getJSONArray("items" );
for(int i=0;i<array.length();i++){
JSONObject snippet =array.getJSONObject(i);
System.out.println(snippet.getJSONObject("snippet").get("title"));
}
JSONObject["items"] not found.
Edit3:
I also tried without Edit2 and just
JSONObject jsonObject = new JSONObject( rest.getForObject(url, Object.class, params));
System.out.println(jsonObject);
No error and I was about to fetch data shown in Postman. But in console printed {}, meaning I might not have gotten the data and won't be able to extract.
I tried extracting using .get System.out.println(jsonObject.get("items"));
and I got the same error JSONObject["items"] not found.
Seems like it could be a format error, again it looks like json already and to use .get, I placed it inside jsonObject but found nothing
Edit4: I can confirm the data I get back is Json (like it says on the doc) using
try {
new JSONObject(rest.getForObject(url, Object.class, params));
} catch (JSONException ex) {
// edited, to include #Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(rest.getForObject(url, Object.class, params));
} catch (JSONException ex1) {
return false;
}
}
return true;
Returned true
Edit5: Seems like the keys is null after trying
String[] keys = JSONObject.getNames(jsonObject);
// iterate over them
for (String key1 : keys) {
// retrieve the values
Object value = jsonObject.get(key1);
// if you just have strings:
String value1 = (String) jsonObject.get(key1);
System.out.println(value);
System.out.println(value1);
}
Cannot read the array length because "keys" is null
The RestTemplate delegates to the underlying Jackson to deserialize the JSON string to a java object .If you get the HTTP response as a generic object type , it will deserialize it into a Map.
You can simply create a POJO with the structure that is the same as the expected JSON response, and then use the Jackson annotations to configure how to deserialize the JSON into this POJO , and get the HTTP response as this POJO class.
Something like :
public class Result {
#JsonProperty("items")
private List<Item> items = new ArrayList<>();
}
public class Item {
#JsonProperty("kind")
private String kind;
#JsonProperty("etag")
private String etag;
#JsonProperty("snippet")
private List<Snippet> snippets = new ArrayList<>();
}
public class Snippet {
#JsonProperty("channelId")
private String channelId;
#JsonProperty("title")
private String title;
}
Then use the following to get the response :
Result result = rest.getForObject(url, Result.class, params);
Once you get the Result POJO , use the favourite library to serialize it into XML.
P.S I just show you the ideas. You have to fine tune the POJO structure
I have data that looks like this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"data": {
"lib": {
"files": [
"data1",
"data2",
"data3",
"data4"
],
"another file": [
"file.jar",
"lib.jar"
],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
Here is the function I'm using to prettify the JSON data:
public static String stringify(Object o, int space) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
I am using the Jackson JSON Processor to format JSON data into a String.
For some reason the JSON format is not in the format that I need. When passing the data to that function, the format I'm getting is this:
{
"status": "success",
"data": {
"irrelevant": {
"serialNumber": "XYZ",
"version": "4.6"
},
"another data": {
"lib": {
"files": [ "data1", "data2", "data3", "data4" ],
"another file": [ "file.jar", "lib.jar" ],
"dirs": []
},
"jvm": {
"maxHeap": 10,
"maxPermSize": "12"
},
"serverId": "134",
"version": "2.3"
}
}
}
As you can see under the "another data" object, the arrays are displayed as one whole line instead of a new line for each item in the array. I'm not sure how to modify my stringify function for it to format the JSON data correctly.
You should check how DefaultPrettyPrinter looks like. Really interesting in this class is the _arrayIndenter property. The default value for this property is FixedSpaceIndenter class. You should change it with Lf2SpacesIndenter class.
Your method should looks like this:
public static String stringify(Object o) {
try {
ObjectMapper mapper = new ObjectMapper();
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new Lf2SpacesIndenter());
return mapper.writer(printer).writeValueAsString(o);
} catch (Exception e) {
return null;
}
}
I don't have enough reputation to add the comment, but referring to the above answer Lf2SpacesIndenter is removed from the newer Jackson's API (2.7 and up), so instead use:
printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
Source of the solution
I decree in a separate folder of the json file type.
These files can not open them and eleborarli with javascript through the $ .getJson ().
But the same thing can do even in java, or rather, I can open a .json in java and process as the function $ .getJson in javascript?
my json is :
node1.json
{
"title": "Risoluzioni problemi 1",
"id": "node1",
"radioList": [{
"text": "possibile problema 1",
"value": "node2"
},
{
"text": "possibile problema 2",
"value": "node3"
},
{
"text": "possibile problema 3",
"value": "node4"
}
]
}
to work with json, javascript / jquery I used:
$.getJSON('node1.json', function (data){
createNextNodes(data);
});
Everything works. Now I would like to do the same thing with ajax requests to a server, the question I asked myself is, as in jquery can i open and edit the files node1.json in a servlet?
even better in Java (servlets) that a function / method that does the same thing for $ .getJson () jquery?
in Java you can make as below
public void parseJson(String path) {
JSONParser jsonp = new JSONParser();
try {
Object obj = jsonp.parse(new FileReader(path));
JSONObject jsono = (JSONObject) obj;
String title = (String) jsono.get("title");
String id = (String) jsono.get("id");
System.out.println(title);///or edit
System.out.println(id);//or edit
JSONArray array = (JSONArray) jsono.get("radioList");
Iterator<String> it = array.listIterator();
while (it.hasNext()) {
Object next = it.next();
System.out.println(next);//or edit
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am trying to deserialize the following string, I am somewhat new to java and I cannot get this to work for the life of me... I am only trying to decode two strings in the object for now. My JSON and Java classes below. I am getting the result variable ok.
{
"result": "true",
"recentlyMarkedTerritories": {
"0": {
"pk_activity": "471",
"fk_activity_type": "100",
"activity_content": "Hhhhh",
"fk_user": "2",
"activity_image": "2_QZe73f4t8s3R1317230457.jpg",
"created": "1317244857",
"activity_status": "1",
"activity_location_lat": "43.515283",
"activity_location_lon": "-79.880678",
"fk_walk": null,
"fk_event_location": "73",
"user_point": "0",
"public_image": "0",
"fk_event_location_lat": "43.515273",
"fk_event_location_lon": "-79.879989",
"profile_image": "2_y9JlkI3CZDml1312492743.jpg",
"user_gender": "1",
"user_dob": "236073600",
"user_nickname": "junoman",
"isFriend": "false",
"profile_image_thumb": "2_y9JlkI3CZDml1312492743_t.jpg",
"activity_image_thumb": "2_QZe73f4t8s3R1317230457_t.jpg",
"relationship_status_idx": "2",
"isBlocked": "false"
},
"1": {
"pk_activity": "469",
"fk_activity_type": "100",
"activity_content": "Jsjsjs",
"fk_user": "1",
"activity_image": null,
"created": "1317244508",
"activity_status": "1",
"activity_location_lat": "43.515283",
"activity_location_lon": "-79.880678",
"fk_walk": null,
"fk_event_location": "73",
"user_point": "0",
"public_image": "0",
"fk_event_location_lat": "43.515273",
"fk_event_location_lon": "-79.879989",
"profile_image": "1_4Cpkofueqnrb1316895161.jpg",
"user_gender": "1",
"user_dob": "116841600",
"user_nickname": "JoePennington",
"isFriend": "false",
"profile_image_thumb": "1_4Cpkofueqnrb1316895161_t.jpg",
"activity_image_thumb": null,
"relationship_status_idx": "1",
"isBlocked": "false"
},
.....
}
}
And my java class below
RecentActivity infoList = null;
Gson gson = new Gson();
infoList = gson.fromJson(JSONString, RecentActivity.class);
public class RecentActivity {
String result;
recentlyMarkedTerritories recentlyMarkedTerritories = null;
public RecentActivity() {
}
public class recentlyMarkedTerritories {
public Set<recentlyMarkedTerritories> pk_activity = new HashSet<recentlyMarkedTerritories>() ;
public recentlyMarkedTerritories() { }
}
}
Please forgive my lack of description but I'm sure the code helps. The JSON is already used in other applications so changing it is not an option.. :(
Thanks!
Here are some nice Tutorials for JSON that will help you out.
GSON
JSON
JSON Example with source code
UPDATED
Try like this,
try {
JSONObject object = new JSONObject(jsonString);
JSONObject myObject = object.getJSONObject("recentlyMarkedTerritories");
for (int i = 0; i < object.length(); i++) {
JSONObject myObject2 = myObject.getJSONObject(Integer.toString(i));
System.out.println(myObject2.toString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
I am not sure of the gson code to write, but the structure of your json looks more like the following java representation (though you might want booleans and ints instead of String fields):
public class RecentActivity {
String result;
Map<String,RecentlyMarkedTerritory> recentlyMarkedTerritories = null;
}
public class RecentlyMarkedTerritory {
String pk_activity;
// other fields
}