How to deserialize json map of String string - java

I have json as below
{
"group": "Mygroup",
"name1": "aaa",
"name2": "bbb"
}
I know that we can deserialize to map. But how can we wrap it inside the object, without any custom deserializer
public class GroupInfo {
private String group
private Map<String, String> names;
}

Gson offers this kind of deserialization. You just need to define a class with the same fields as the JSON keys of the JSON being parsed.
Article on using Gson for this usage - https://dzone.com/articles/deserializing-json-java-object
Gson repo - https://github.com/google/gson
If you aren't dead set on JSON, I would recommend looking into Protocol Buffers. Protocol Buffers offer this type of functionality out of the box, are language agnostic (to a large extent anyways), and they're usually much faster than JSON.
Protocol Buffers - https://developers.google.com/protocol-buffers/docs/tutorials

Related

Serialising a Java Map with Jackson

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.

Preserving parts of raw content during JSON and/or XML deserialisation

I am looking for a mechanism to deserialise a JSON representation of a map with polymorphic values out of the following string {"name": "your doubles", "values": [25.0, 15.0]} and into an instance of HashMap<String, Serializable>. As I cannot pass individual value types to the deserialiser (even though I know them) for every element of type Serializable I want to keep the original JSON string representation to deserialise it into a concrete type separately. I could use fasterxml or GSON or any other library that can do the job in a sensible manner.
I would have the same question for XML serialisation.
So for the above example I would like to generate a map, which values equal "\"your doubles\"" and "[25.0, 15.0]". Effectively, I need a custom deserializer that preserves the raw data whenever it finds a node that needs to be deserialized into a Serializable.
There is a straightforward solution to the problem, here is using Gson:
Gson gson = builder
.registerTypeAdapter(Serializable.class, new SerializableDeserializer())
.create();
private static class SerializableDeserializer implements JsonDeserializer<Serializable> {
#Override public Serializable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return json.toString();
}
}
However, if I am not mistaken this solution actually parses the node under the Serializable and then serialises it back. So if the value is large I will end up parsing it twice.
Additionally, I failed to implement this same solution for XML using the fasterxml XML parser. The problem there is that, as mentioned above, it actually parses the node and then serialises is back, but into JSON.
Any better JSON options?
Any XML solution?

Deserialize only some fields of JSON objects array (Java)

Given this JSON response I get from an website :
{
"Items":
[
{ "Name":"Apple", "Price":12.3, "Quantity":30 },
{ "Name":"Grape", "Price":3.21, "Quantity":60 }
],
"Date":"21/11/2010"
}
How could i deserialize this JSON, splitting it in an array called Fruits, containing only name and quantity ? I don't care about date field or other fields like price.
My class should look like:
class Fruit{
String name;
String quantity;
}
And this is the array:
Fruit myfruits[] = new Fruit [this number depends on JSON response I get]
How could I achive this ?
I've tried to give my best explanation, if it is still not clear, feel free to ask.
P.S: btw, the real JSON response has many more fields
You need to ignore the fields you don't wont.
Each serialization frameworks does it in different ways.
In some you can add annotations to you POJO, or set it with the serializer instance
Using Gson:
Gson ignore json field and deserialize
Using Jackson:
Ignoring new fields on JSON objects using Jackson

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