This question already has answers here:
How can I convert JSON to a HashMap using Gson?
(16 answers)
Converting deeply nested json to java object and vice versa
(3 answers)
Closed 4 years ago.
I want to get some ideas to handle a JSON structure like this.
Especially for the '/' key.
{
"tree":{
"/":"1234567890"
},
"parents":null
}
I created this (works if I replace / with slash in the given JSON)
private class Test {
private SubDirectory tree;
private String parents;
}
private class SubDirectory {
private String slash;
// private String /; obviously not working :D
}
using Gson with a InputStreamReader and then:
Test p = gson.fromJson(reader, Test.class);
So my first idea is to check reader and replace that / to slash.
But really ?! ...
Related
This question already has answers here:
How do I use a custom Serializer with Jackson?
(11 answers)
Closed 1 year ago.
I want to write a function that only serializes a POJO with given implicit field names.
For example,
class Car{
public int id;
public String type;
public Manufacture manufacture;
}
Class Manufacture{
public int id;
public String name;
}
if I want to serialize a Car object with a given list(i.e. [Car.id, Car.Manufacture.name])
Then I want to get
{
Car:{
id: xxx,
Manufacture: {
name: xxx
}
}
}
Another example, given list = [Car.type]
Then I should get
{
Car:{
type: xxx
}
}
I am currently trying to override the serializeAsField method to check if the field is in the given list, but the problem here is that I don't know the depth, then I cannot correctly compare the current field with the list.
How could I achieve it? Are there any other ways?
Mark the unwanted fields with the #JsonIgnore annotation.
On-the-fly filtering
Here is a Baeldung article that discusses using a filter to
determine which fields are serialized:
https://www.baeldung.com/jackson-serialize-field-custom-criteria
I suspect that is the answer you want.
This question already has answers here:
Using Enums while parsing JSON with GSON
(7 answers)
Closed 2 years ago.
Is there a GSON equivalent annotation for Jackson's #get:JsonValue?
I have the below enum and I need the GSON annotation as well.
enum class TransactionType(#get:JsonValue val code: Int) { ... }
It was:
enum class Type(#get:JsonValue val code: Int, val description: String) {
#SerializedName("0") NEGATIVE(2, "negative amount "),
#SerializedName("1") CREDIT(3,"Credit."),
#SerializedName("2") WAGERS(6,"wager"),
#SerializedName("3") ZERO(8, "zero.")
}
Reference:
https://javadoc.io/doc/com.google.code.gson/gson/2.8.1/com/google/gson/annotations/package-summary.html
This question already has an answer here:
Flattening nested attributes in Jackson
(1 answer)
Closed 2 years ago.
I am trying to deserialize nested JSON into a single DTO in a Spring Boot application.
The JSON:
{"productId": "xyz123",
"description": "some_description",
"value": "123",
"boughtOnDate": "2020-05-20 14:22:58.000662",
"details": {
"material": "some_material",
/// another 20 entries
}
}
The DTO:
#JsonIgnoreProperties(ignoreUnknown = true)
#Entity
public class Item {
#Id
private String productId;
private String description;
private Integer value;
private Timestamp boughtOnDate;
private String material;
// another 20 fields that are in the nested part of the json
// getters & setters
The current solution I have is to unpack nested json in the Item class like so:
#JsonProperty("details")
private void unpackNestedJson(Map<String, Object> details) {
this.material = (String) details.get("material");
// and another 20 lines for unpackacking the rest from the nested part
While unpackNestedJson works fine and does its job, it feels cumbersome as there is a lot of data to unpack from the nested part of the JSON (all entries below and above 'details' from JSON should go as fields into Item entity class only). My question would be - is there a more simple/elegant way of unpacking the nested JSON into a single DTO? Any help appreciated.
No, i think that's the right way to do, but if you want to explore another option, you could have an Details object inside Item with a material property. Then you could just have some getters/setters with the parent DTO delegating to the material property to still achieve the same behavior.
This question already has answers here:
Create new object using reflection?
(2 answers)
What is reflection and why is it useful?
(23 answers)
Closed 7 years ago.
Suppose I have this class:
public class Person {
private String name;
private int age;
//setters and getters
...
}
The following code is not correct, but I want something similar.
String className="Person";
String att1 = "name";
String att2 = "age;
object o = createClassByName(className);
setValueForAttribute(o,att1,"jack");
setValueForAttribute(o,att2,21);"
Are you familiar with hashes?
I think you could use a HashMap, which is a common Hash implementation built into the Java library:
HashMap<String,Object> person1 = new HashMap<String,Object>();
person1.put("className", "Person");
person1.put("name", "Jack");
person1.put("age", 21);
Everytime you want to change the values, do: person1.put("name", "Jill")
And to get the values, it's person1.get("name")
If you want to take the class into account, you'll have to get the className and manually compare it in your code, to do different things according to the "class" of the object (which in reality is a HashMap, but nevermind).
Small reminder: doing things this way is considered very messy ;)
I am trying to parse the JSON from this link: https://api.guildwars2.com/v2/items/56 , everything fine until i met the line: "infix_upgrade":{"attributes":[{"attribute":"Power","modifier":4},{"attribute":"Precision","modifier":3}]} ...
If i dont get this wrong: infix_upgradehas 1 element attributes inside him. attributes has 2 elements with 2 other inside them. Is this a 2 dimension array?
I have tried (code too long to post):
JsonObject _detailsObject = _rootObject.get("details").getAsJsonObject();
JsonObject infix_upgradeObject = _detailsObject.get("infix_upgrade").getAsJsonObject();
JsonElement _infix_upgrade_attributesElement = infix_upgradeObject.get("attributes");
JsonArray _infix_upgrade_attributesJsonArray = _infix_upgrade_attributesElement.getAsJsonArray();
The problem is that I dont know what to do next, also tried to continue transforming JsonArray into string array like this:
Type _listType = new TypeToken<List<String>>() {}.getType();
List<String> _details_infusion_slotsStringArray = new Gson().fromJson(_infix_upgrade_attributesJsonArray, _listType);
but im getting java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT which i guess comes from the attributes...
With a proper formatting (JSONLint, for example, checks if the JSON data is valid and does the formatting, which makes the structure more clear than what the GW link gives), attributes looks actually like this:
"attributes": [
{
"attribute": "Power",
"modifier": 4
},
{
"attribute": "Precision",
"modifier": 3
}
]
So it's an array of JsonObject and each object as two key-value pairs. This is why the parser throws an error because you require that this array contains only String which is not the case.
So the actual type is:
Type _listType = new TypeToken<List<JsonObject>>(){}.getType();
The problem is that I dont know what to do next
Hold on. You are using Gson and Java is an OO language so I suggest you to create classes.
This would be easier for you to fetch the datas afterward and for the parsing since you just need to provide the class of the actual class the JSON data represents to the parser (some edge-cases could be handled by writing a custom serializer/deserializer).
The data is also better typed than this bunch of JsonObject/JsonArray/etc.
This will give you a good starting point:
class Equipment {
private String name;
private String description;
...
#SerializedName("game_types")
private List<String> gameTypes;
...
private Details details;
...
}
class Details {
...
#SerializedName("infix_upgrade")
private InfixUpgrade infixUpgrade;
...
}
class InfixUpgrade {
private List<Attribute> attributes;
...
}
class Attribute {
private String attribute;
private int modifier;
...
}
and then just give the type to the parser:
Equipment equipment = new Gson().fromJson(jsonString, Equipment.class);
Hope it helps! :)