Store object as attribute in json - java

I am trying to make a simple console farm game using Java and JSON. I have a player stored in json in the following format:
{
"coins":5,
"name":"playerName",
"inventory":{
some inventory items...
}
}
But now I want to save a farm object as attribute of this player in such a way:
{
"coins":5,
"name":"playerName",
"inventory":{
some inventory items...
},
"Farm": {
"capacity": 1,
"plantedSeeds": HashMap<Integer, VegetableItem> plantedSeeds
}
}
Does anyone have any idea how I can save my player in this way using Java and Jackson?
Thanks!
UPDATE
I figured it out,
i simply needed to create a seperate JSONObject, store all the values I wanted in that object, and then add the JSONObject as the attribute for the player object

Related

Set public variables by name (from JSON)

I am using Room and Volley to get data from a generic web service that only returns column and value for each row of the selected table.
The thing is that I don't want to modify the web service to return a specific data tree by table.
So having :
{"columns": {
"0": [{"column":"name","value":"pepe"},{"column":"age","value":20}],
"1": [{"column":"name","value":"paco"},{"column":"age","value":23}]
}}
.. I want to be able to fit that response creating an instance of the following class for example...
public class Person {
String name = "";
int age = 0;
}
So people make the pojo from their responses to consume each object with gson like...
{"persons": {
"person": [{"name":"pepe","age":20},{"name":"paco","age":23}]
}}
Person p = gson.fromJson(jsonString, Person.class);
So i want to be able as im invoking the table person in the web service to return that generic json and convert it to a custom class because the columns are the same in the response and in the class itself.
Is there a possibility to load that column name and ask the object the type of data and parse it properly in a few lines of code...? ...Or ill need to loop de JSONObject to get the specific variable to later build the object in the constructor...?
THX

Pass object inside existing model object, where the new object parameters are not defined and may change

Problem: I have a request body where I have a predefined POJO class, inside this class I need to add another object as parameter. This new object at a given time may have random properties/attributes/params. How can I achieve this?
{
"id": "{{id}}",
"enableTouchId": true,
"idleLogoutMinutes": 10,
"platformSpecificPreferences": {
"ios": {
"terms": "1234",
"privacy": "12345"
},
"web": {
"terms" : "abc"
},
"android": {
"newProperty" : "newValue"
}
}
}
So the new object I am trying to add is platformSpecificPreferences, which when hit using rest calls might or might not have all the properties shown here, which is why I cannot use redefined POJO class for platformSpecificPreferences and create its object.
Solution I tried:
I thought of using JsonObject inside request body, which makes
#JsonProperty("platformSpecificPreferences")
private JsonObject platformSpecificPreferences;
but the problem is, I am not able to hit the api as it doesnt accept this parameter and gives 404.
Thanks in advance.
You can use, kind must a predefined pojo for platformSpecificPreferences but in the pojo you need to ignore values that are not given in the rest call!
You can do this with a json annotation:#JsonIgnoreProperties(ignoreUnknown = true) in the Pojo above the class.

Detecting object types in JSON document

I have a text file as input which contains Employees. Now I need to refactor the code and the JSON can either contain an Employee[] array or a Building[] array. I am using Jackson, and there are enums in my Java class.
{
Employee[]
}
{
Building[]
}
I have code to selectively parse each document, but how can the code detect whether it is an Employee doc or a Building doc?
I know it's kind of a bad design, but there are some constraints for which I am doing so.
I need something like this:
boolean isBuildingDoc(String json);
boolean isEmployeeDoc(String json);
How can I do this?
My advice would be to add a top level property to your json called 'info'.
For example:
{
"info": {
"document_type": "employee"
},
"content": {
// rest of your json goes here...
}
}
Put the old json you used to generate in 'content'. Then, when you parse your json file, you can easily check the info.document_type flag to see what document type you are working with.
However, if you do not have control over the json that is being parsed (e.g. if it is being sent from another program), then this approach will not work.
You can use tree modal of jackson to detect Employee or Building node.
E.g.
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
if(node.get("Employee") != null){
//handle it according to employee
}
else if(node.get("Building ") != null){
//handle it according to building
}
Note : Do remember one thing, get method searches for field in child elements also, So if your Employee array contains Building field as a child element, then this method will not work.

Convert a JSON string to a JSONObject in java pojo using GSON

I have my class (assume getters/setters defined) :
public class Keyword
{
private String keyword;
private JSONObject keywordData;
}
}
And my JSON looks like this :
{
"keyword": "help",
"keywordData": {
"line1": "This is line1",
"line2": "this is line 2"
}
}
I am able to get the "help" word in my java class, but not keywordData.
I want to save the data inside keywordData as JSON itself. (The number of lines will increase, thats why I want to store it as JSON itself. Also, I don't want to use a list for line1, line2.. and son on)
Does anyone know what's wring with my POJO class?

getting the values of array from javascript to java as list

var catids = new Array();
I have a catids array where i store the checked checkbox values like the below one.
cat = $("input[name=catChkBox]:checked").map(function () {
return $(this).data('name');
}).get().join(",");
the cat variable forms something like this 1,2,3..
I want to send this "cat" to a java method and print those values.
I pass the values to java through a dwr call like this
DataHandler.getTasks( categories, {callback:function(data){
}, errorHandler:function(){
},async:false
});
I have configured dwr for pojo. should I configure anything for parameters?
I tried the below code but I didn't get anything.
public List<Facade> getTasks(String myIds){
String[] ids = catids .split(",");
System.out.println("-------size of cat id------------" + myIds.length);
for (int i=0; i<myIds.length;i++)
System.out.println(myIds[i]);
//finally it will return a pojo which i l be receiving it in data of dwr call.
-------size of cat id------------ is 1
myIds[i] prints nothing
I need it as an integer back.
What mistake am I doing ?
I will do it in this way.
JavaScript creates json object like this {"categoryIds": [1,2,3,4,5]}
Java converter convert json to java POJO object using for example Gson or Jackson library.
After convert you can work with java POJO object which have list of categories.
If you use this solution your code will be more clear and you will be able to share more objects between JavaScript and Java using the same clear solution.
Example (pseudo code)
CategorList class
public class CategoryList {
private ArrayList<Category> categoryList;
// getters and setters
}
Converter
public class CategoryListConverter {
public CategoryList convert(String json) {
Gson g = new Gson();
CategoryList cl = g.fromJson(json, CategoryList.class);
return cl;
}
}
I tried the code it workd fine
getTasks("1,2,3");
check what the value of categoriesIds is sent to getTask
Send this as a form parameter from webpage. Then get this from HttpServletRequest request object in java.
request.getParameter('categoryId');

Categories