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);
}
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'm building an Nativesctipt app for Android that uses Firebase as backend and I'm using the native Firebase Android library v2.4.0
I can insert objects in Firebase just fine using the following {N} Javascript syntax
var user = new java.util.HashMap();
user.put("name", viewModel.get("name"));
user.put("lastName", viewModel.get("lastName");
var address = new java.util.HashMap();
address.put("address", viewModel.get("address");
address.put("number", viewModel.get("number");
address.put("city", viewModel.get("city");
user.put("address", address);
ref = new Firebase("https://my-firebase-app-url/users");
refUser = ref.child(viewModel.get("username"));
refUser.setValue(user);
The problem with this is that I have to manually convert every javascript object into a java hashSet (and back) and I wanted to do it using a JSON to HashMap library so I have imported the java Jackson library into my {N} app.
According to this site here's the way to convert a JSON to a HashMap in Java using Jackson:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"mkyong\", \"age\":29}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
I'm looking for a way to translate that into a {N} Javascript code that will do it for me but I'm unable to use generics notation in {N} Javascript. Does anybody know how I could do it? I have tried some ways but all of them crashed the application. Here's an {N} Javascript snippet does not work:
var ObjectMapper = com.fasterxml.jackson.databind.ObjectMapper;
var TypeReference = com.fasterxml.jackson.core.type.TypeReference;
var mapper = new ObjectMapper();
var map = mapper.readValue(JSON.stringify(user), new TypeReference());
refUser.setValue(map);
Any help is greatly appreciated.
I have a JSON response which looks like this:
String resp = "{"name":"Renold","age":"16"}"
And I have a POJO named "Person" which contains the attributes 'Name' and 'Age'. How do I extract the attributes from the JSON response and assign them to the POJO? I have already tried GSON and the object gets incorrectly assigned as "Name = name" and "Age = age" instead of the actual response.
Any other suggestions, good lads? :)
EDIT: This is what I used with GSON
Gson gson = new Gson();
final Person p= gson.fromJson(response, Person.class);
This left me with:
p.Name = name;
p.Age = age;
instead of p.Name = Renold.
You can try this with Genson:
String resp = "{"name":"Renold","age":"16"}"
Genson genson = new Genson();
Person person = genson.deserialize(resp, Person.class);
I guess you have to use #SerializedName to map Name to name
check this pojo parse gson with invalid java names
In your Pojo you have to annotate like this.
#SerializedName("name")
private final Name;
Please try serialization using the JObject class using org.json. e.g
JSONObject jsonObj = new JSONObject("{\"name\":\"Renold\",\"age\":\"16"\"}");
Then get the properties:
jsonObj.get("name");
If you're using maven you can include the Jackson dependency. That will map things automagically.
I have used the same scenario you have described and found no issues with your code except the String representation you have used. I have put my code at pastebin. This sample project should resolve your issue of json format.
The string in your response should be:
String response = "{\"name\":\"Renold\",\"age\":16}"
I have some model classes like Customer, Product, etc. in my project which have several fields and their setter-getter methods, I need to exchange objects of these classes as a JSONObject via Sockets to and from client and server.
Is there any way I can create JSONObject directly from the object of model class such that fields of the object become keys and values of that model class object become values for this JSONObject.
Example:
Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....
And I create JSON Object as:
JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.
Which gets me something like:
{"name":"Foo Bar","city":"Atlantis"...}
Please note that, in some of my model classes, certain properties are itself an object of other model class. Such as:
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
In a case like above, as I'd expect, the yielded JSON object would be:
{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}
I know I could create something like toJSONString() in each model class and have the JSON-friendly string created and manipulate it then, but in my previous experiences of creating RESTful service in Java (which is totally out of context for this question), I could return JSON string from the service method by using #Produces(MediaType.APPLICATION_JSON) and have the method returning object of model class. So it produced JSON string, which I could consume at the client end.
I was wondering if it's possible to get similar behavior in current scenario.
Google GSON does this; I've used it on several projects and it's simple and works well. It can do the translation for simple objects with no intervention, but there's a mechanism for customizing the translation (in both directions,) as well.
Gson g = ...;
String jsonString = g.toJson(new Customer());
You can use Gson for that:
Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
Java code:
Customer customer = new Customer();
Product product = new Product();
// Set your values ...
Gson gson = new Gson();
String json = gson.toJson(customer);
Customer deserialized = gson.fromJson(json, Customer.class);
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use gson to achieve this. You can use following code to get the json then
Gson gson = new Gson();
String json = gson.toJson(yourObject);
I have used XStream Parser to
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("p", Product.class);
String jSONMsg=xstream.toXML(product);
System.out.println(xstream.toXML(product));
Which will give you JSON string array.