I am using Amazon's APIGateway service client side. When you make a request the data returned is stored in a Model data type that the schema is set up beforehand. the calls look like this:
MyModel myModel = client.settingsPost();
String volume = myModel.getVolume();
the schema for this simple object would look like this:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "MyModel",
"type": "object",
"properties" : {
"volume" : { "type" : "string" }
}
}
I would like to convert the Model returned directly to JSON instead of having to go manually reconstruct a new JSONObject from each value of this Model. The Models seem to be very simple and I cant even iterate through them. But I wonder if there is a way to convert them using the GSON library somehow?
EDIT: I am using the APIGateway SDK generated to Java.
Using Jackson:
ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(myModel);
Using Gson:
Gson gson = new Gson();
String json = gson.toJson(myModel);
Related
I need GSON mapper to throw an exception if json contains unknown fields. For example if we have POJO like
public class MyClass {
String name;
}
and json like
{
"name": "John",
"age": 30
}
I want to get some sort of message that json contains unknown field (age) that can not be deserialized.
I know there is out-of-box solution in Jackson mapper, but in our project we have been using Gson as a mapper for several years and using Jackson ends up in conflicts and bugs in different parts of project, so it is easier for me to write my own solution than using Jackson.
In other words, I want to know if there is some equivalent to Jackson's DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES in Gson. Or maybe if it can be done using Gson's DeserializationStrategy other than using reflections
I believe you cannot do it automatically with Gson.
I had to do this in a project at work. I did the following:
Gson GSON = new GsonBuilder().create();
(static final) Map<String, Field> FIELDS = Arrays.stream(MyClass.class.getDeclaredFields())
.collect(Collectors.toMap(Field::getName, Function.identity()));
JsonObject object = (JsonObject) GSON.fromJson(json, JsonObject.class);
List<String> objectProperties = object.entrySet().stream().map(Entry::getKey).collect(Collectors.toList());
List<String> classFieldNames = new ArrayList<>(FIELDS.keySet());
if (!classFieldNames.containsAll(objectProperties)) {
List<String> invalidProperties = new ArrayList<>(objectProperties);
invalidProperties.removeAll(classFieldNames);
throw new RuntimeException("Invalid fields: " + invalidProperties);
}
I need GSON mapper to throw an exception if json contains unknown fields. For example if we have POJO like
public class MyClass {
String name;
}
and json like
{
"name": "John",
"age": 30
}
I want to get some sort of message that json contains unknown field (age) that can not be deserialized.
I know there is out-of-box solution in Jackson mapper, but in our project we have been using Gson as a mapper for several years and using Jackson ends up in conflicts and bugs in different parts of project, so it is easier for me to write my own solution than using Jackson.
In other words, I want to know if there is some equivalent to Jackson's DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES in Gson. Or maybe if it can be done using Gson's DeserializationStrategy other than using reflections
I believe you cannot do it automatically with Gson.
I had to do this in a project at work. I did the following:
Gson GSON = new GsonBuilder().create();
(static final) Map<String, Field> FIELDS = Arrays.stream(MyClass.class.getDeclaredFields())
.collect(Collectors.toMap(Field::getName, Function.identity()));
JsonObject object = (JsonObject) GSON.fromJson(json, JsonObject.class);
List<String> objectProperties = object.entrySet().stream().map(Entry::getKey).collect(Collectors.toList());
List<String> classFieldNames = new ArrayList<>(FIELDS.keySet());
if (!classFieldNames.containsAll(objectProperties)) {
List<String> invalidProperties = new ArrayList<>(objectProperties);
invalidProperties.removeAll(classFieldNames);
throw new RuntimeException("Invalid fields: " + invalidProperties);
}
I am invoking API which returns JSON as a response which I am parsing into POJO using Jackson. It is working fine but
failing for below JSON array format,
{
...
"data" : [
{
"2017-12-05 21:40:33":"1537"
},
{
"2017-12-07 23:51:16":"1539"
},
{
"2017-12-12 22:57:10":"1539"
}
],
...
}
This date in key is generated at time of data captured in server side, my application invoking API which returns above format
of JSON so can you please let me know how I can parse this JSON in Java POJO.
Thanks.
Something similar to following.
public class POJO {
...
List<Map<String,String>> data;
...
}
You can also format the key as java.util.Date if needed, registering the date type serializer in the Jaskson's object mapper builder.
I like the idea of having a standard for JSON serialization in Java, javax.json is a great step forward you can do an object graph like this:
JsonObject jsonObject3 =
Json.createObjectBuilder()
.add("name", "Ersin")
.add("surname", "Çetinkaya")
.add("age", 25)
.add("address",
Json.createObjectBuilder()
.add("city", "Bursa")
.add("country", "Türkiye")
.add("zipCode", "33444"))
.add("phones",
Json.createArrayBuilder()
.add("234234242")
.add("345345354"))
.build();
That's it, but how can I serialize a pojo or simple Java object(like a Map) direct to JSON?, something like I do in Gson:
Person person = new Person();
String jsonStr = new Gson().toJson(person);
How can I do this with the new standard API?
Java API for JSON Processing (JSR-353) does not cover object binding. This will be covered in a separate JSR.
See JSR-367, Java API for JSON Binding (JSON-B), a headline feature in Java™ EE 8.
Document: Json Binding 1.0 Users Guide
// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);
// Deserialize back
dog = jsonb.fromJson("{name:\"Falco\", age:4, bitable:false}", Dog.class);
Maybe it's because this question is almost 5 years old (I didn't check which java release has these classes) but there is a standard way with javax.json.* classes:
JsonObject json = Json.createObjectBuilder()
.add("key", "value")
.build();
try(JsonWriter writer = Json.createWriter(outputStream)) {
writer.write(json);
}
My JSON file's content is :
{
"MJ" : "Michael Jordan",
"KB" : "Kobe Bryant",
"KG" : "Kevin Garnet"
}
Now it is easy to convert this file (or string) to a Java class (e.g: java.util.HashMap) if I use Gson or Jackson or JsonSimple or another Java/JSON third-party library. E.g., I can use Gson like this:
//this returns the string above
String jsonString = TestReader.getStrFromJSonFile();
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
HashMap<String, String> map = gson.fromJson(jsonString, type);
But,if my JSON file contains comments, most of the third-party libraries will not work.
e.g.:
{
//Bulls
"MJ" : "Michael Jordan",
/*Lakers*/
"KB" : "Kobe Bryant",
//Boston Celtics
"KG" : "Kevin Garnet"
}
Now I'm even confused after googling and stackoverflowing a lot. I have two questions:
Can a JSON file really contain any comments? I think it can because I see a lot of this in JSON files everyday. But >>> (links)
If it can, how can I solve my problem?
Jackson supports comments if you enable that feature on the parser you use:
https://fasterxml.github.io/jackson-core/javadoc/2.10/com/fasterxml/jackson/core/JsonParser.Feature.html