Serialising a Java Map with Jackson - java

I am using Jackson library for serialising JSON,
having Serialising a Java Map, for ex, map<String,String> has
{<color, green>,<color, blue>}
I want this to be serialised as
"colormap":[{"key": "color":, "value":"green"}, {"key": "color:, "value":"blue"}]
but its always serialising as
"colormap":[{"color":"green"}, {"color:"blue"}]

Your output JSON is an array, not a map- Without looking at your code it's hard to tell what the underlying data structure is,but to do what you're looking for you might consider a class such as:
class Thing {
private String key ;
private String value ;
/// add accessors as needed
}
and then declare your colormap as List<Thing>. This should seralize your data per your expectation.

Related

Java Spring omits fields when making a JSON

public class ConnectedEntry {
private EntryInScores scores;
private EntryInValues values;
private String someString;
public ConnectedEntry(EntryInScores scores, EntryInValues values) {
this.scores = scores;
this.values = values;
this.someString = "Adasd";
}
I have an object that looks more or less like this, and I use it as a GET response for my API. scores and values are both database entities. I wanted to add a String to the response with some additional information.
What happens is that the objects are properly turned into a JSON and they show up in the response, but the string is omitted, with no error: it's just not there.
I tried wrapping the string in a wrapper class, but it didn't help.
What could I do?
Usually Spring uses Jackson as the default converter from objects to JSON. In order for Jackson to convert to JSON you must provide getters, so that Jackson can get and convert those values. As I can see in your representation you don't have any getters. Try providing getters for the fields that you wish to convert. Never make fields public!
You can go for creating json object and put the data as key value pair to resolve this issue.
Happy Coding!!!

Change naming of attributes in json without #JsonProperty

I have to convert my json from camelCase to kebab-case.
Example:
My Json:
{
"disclaimerConfirmed" : true
}
And I need:
{
"disclaimer-confirmed" : true
}
I cannot use #JsonProperty because it rename this atributes permanently. I am looking for something which will consume Json (can be as String) and returns modified json(as String).
Jackson supports naming strategies so you could read the input String to map (with camelCase strategy) and then write the map back to a String (with kebab-case which is natively supported );
Specific method you need to switch these conventions in ObjectMapper without annotations is:
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.*);
You can have different serializers for different cases or you can create pojo with #JsonProperty and use those where-ever required.
For example,
class A {
private String disclaimerConfirmed;
}
class AkebabCase {
#JsonProperty("disclaimer-confirmed")
private String disclaimerConfirmed;
}
So, if you want to serialize to kebab-case you can use converters to convert A to AkebabCase and then serialize.

combine JSON object and JSON array to get another JSON object in Java

I have List<Person> where its JSON output is like:
[{"name":"john","email":"john#email.com"},
{"name":"daniel","email":"daniel#email.com"},
{"name":"thomas","email":"thomas#email.com"}]
and a count of the persons where its JSON format is like: {"number":3}
How can I combine the above two to get the result:
{
"number":3,
"persons":[{"name":"john","email":"john#email.com"},
{"name":"daniel","email":"daniel#email.com"},
{"name":"thomas","email":"thomas#email.com"}]
}
my Java code is jersey2 based JAX-RS application. to make more clear, I have a list of Person fetched from database and i also have an integer variable number. and combine the List and the integer variable to get above result in an efficient and robust way.
Since you are using a framework that already does conversion to JSON automatically, the easiest way would be to just return a new object.
public class Result {
private int number;
private List<Person> persons;
//leaving creation of constructor to you
}
And then just instantiate that object and return it.
When you want to map Object to json directly or want to convert json to object, you can use GSON library . this will give you more flexibility and control.
Download link - http://code.google.com/p/google-gson/
Tutorial link - http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Get JSONobjects from string

So i have a string which contains multiple JSONobjects and looks like this:
[{"one":"1","two":"2","three":"3"},
{"one":"4","two":"5","three":"6"},
{"one":"7","two":"8","three":"9"}]
How can i iterate through this string using java and get every object? Is it possible using JSON api, or i should make parser by myself?
GSON library is a good option to convert java object to json string and vise versa.
for converting json to java object use: fromJson(String, Class)
for converting java object to json string use: toJson(Object)
In your case it's a List of Object.
sample code:
class MyPOJO {
private String one;
private String two;
private String three;
// getter & setter
}
String jsonString = "[{\"one\":\"1\",\"two\":\"2\",\"three\":\"3\"}, {\"one\":\"4\",\"two\":\"5\",\"three\":\"6\"}, {\"one\":\"7\",\"two\":\"8\",\"three\":\"9\"}]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(jsonString, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
Note: The name of variable in your java POJO class should be same as JSON string.
Find more examples...
You Should defiantly use the Json API, you can download the jar from here and simply use
JSONArray myArray = new JSONArray(yourString);
for (int i=0; i < myArray.length(); i++)
{
JSONObject currentOb = myArray.get(i);
doSomthing(currentOb);
}
It is obvious that you should use a JSON library. Existing libraries are tested and validated. In very rare conditions you may need to write your own parser, your own implementation. If that is the case, I think you should double check your design. Because you might be doing something wrong if the existing library is in conflict with your design.
Library selection depends on your environment and your performance requirements.
In my case, Spring3 is the environment and the JSON objects are huge (10-20MB), and inserts occur on existing JSON objects. We prefer Jackson. Jackson's performance is outstanding. An independent performance comparison is in here. You will see that the Jackson outperforms GSon in here.

What is the most suitable Java data structure for representing JSON?

I' m developing a RESTful Android mobile client. Information exchange between my app and server is in JSON. So I' m now a little bit confused what data structure choose for represent JSON responses and data because there a lot of them. I've just stopped with LinkedHashMap<> but as far as i know JSON is unordered. Across the Internet I saw people use Map<> or HashMap<> for this. So the question - what is the best data structure for this purpose? Or if there is no a univocal answer - pros and cons of using data structures I' ve mentioned.
I would disagree with the first answer. The REST paradigm was developed so that you would operate with objects, rather than operations.
For me the most sensible approach will be if you declare beans on the client side and parse the json responses and request through them. I would recommend using the GSON library for the serialization/ deserialization. JsonObject/ JsonArray is almost never the best choice.
Maybe if you give examples of the operations you are about to use we might be able to help more precisely.
EDIT: Let me also give a few GSON Examples. Let's use this thread to compare the different libraries.
In the most cases REST services communicate objects. Let's assume you make a post of product, which has reference to shop.
{ "name": "Bread",
"price": 0.78,
"produced": "08-12-2012 14:34",
"shop": {
"name": "neighbourhood bakery"
}
}
Then if you declare the following beans:
public class Product {
private String name;
private double price;
private Date produced;
private Shop shop;
// Optional Getters and setters. GSON uses reflection, it doesn't need them
// However, better declare them so that you can access the fields
}
public class Shop {
private String name;
// Optional Getters and setters. GSON uses reflection, it doesn't need them
// However, better declare them so that you can access the fields
}
You can deserialize the json using:
String jsonString; // initialized as you can
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
Product product = gson.fromJson(jsonString, Product.class);
// Do whatever you want with the object it has its fields loaded from the json
On the other hand you can serialize to json even more easily:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm"); // setting custom date format
Gson gson = gsonBuilder.create();
String jsonString = gson.toJson(product);
Are you talking about receiving and parsing the JSON string from a server request?
For that you can use:
import org.json.JSONArray;
import org.json.JSONObject;
Using these, I read through my JSON array from my POST request and store the resulting information in Class objects in my project.
For each item in JSONArray, you can extract the JSONObject and attributes like this:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonObject.getString("text");
}
As far as actually storing the data, like mentioned above, JSON data can come in a wide array of formats depending on the source, and as such, it is usually parsed on the client end and saved in your application Class objects for use. Or more generically, you could store the data using Map<String, Object>
This is easily the best answer I've seen:
https://dzone.com/articles/which-is-the-right-java-abstraction-for-json
Summary: there are three abstrations: pojos, maps and lists, and custom classes to represent objects, arrays, and primitives. There are advantages and disadvantages to each, with no clear winner.
Pojos have the biggest advantages, but you can't always use them. Use them if you can, and use the others if you must.
If you are doing anything other than the most simple mapping then you should use a full class structure. Create your class hierarchy as a mirror of the data structure in JSON and use Jackson to map the JSON directly to the class hierarchy using the ObjectMapper.
With this solution you don't have any casting of Object to Map or messing around with JSONObject or JSONArray and you don't have any multi-level map traversal in your code. You simply take the JSON string, feed it to the ObjectMapper, and get a your Object, which contains child objects (even collections) automatically mapped by the ObjectMapper.
I've used xstream to serialize JSON, in the following way:
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("myAlias", MyClass.class); // requires a no argument constructor
System.out.println(xstream.toXML(product));
Ok, the gentleman in the comments wants a deserialization example, here you are:
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.alias("myAlias", MyClass.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());
Let me know if you need further assistance...

Categories

Resources