Parsing JSON into Jackson using a stream/object approach - java

I have a JSON file which can have multiple types.
For example:
{
"dog": {
"owner" : "John Smith",
"name" : "Rex",
"toys" : {
"chewtoy" : "5",
"bone" : "1"
}
},
"person": {
"name" : "John Doe",
"address" : "23 Somewhere Lane"
}
// Further examples of dogs and people, and a few other types.
}
I want to parse these into objects. ie. I want to create a Dog object with owner/name/toys attributes, and person with name/address attributes, and use Jackson to read through and create objects out of them.
The ordering matters - I need to know that Rex came before John Doe, for example. I would prefer to do with a stream like approach (ie. read and parse Rex into the Dog object, do something with it, then discard it, then move onto to John Doe). So I need a stream based approach.
I can't figure out how to use both the stream reading API (to go through in order) and the ObjectMapper interface (in order to create Java objects out of JSON) to accomplish this.

To do this, you need to use an object mapper with your factory
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
...
private static ObjectMapper mapper = new ObjectMapper();
private static JsonFactory factory = mapper.getJsonFactory();
Then create a parser for the input.
JsonParser parser = factory.createJsonParser(in);
Now you can mix calls to parser.nextToken() and calls to parser.readValueAs(Class c). Here is an example that gets the classes from a map:
Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
classMap.put("dog", Dog.class);
classMap.put("person", Person.class);
InputStream in = null;
JsonParser parser = null;
List<Object> results = new ArrayList<Object>();
try {
in = this.getClass().getResourceAsStream("input.json");
parser = factory.createJsonParser(in);
parser.nextToken();// JsonToken.START_OBJECT
JsonToken token = null;
while( (token = parser.nextToken()) == JsonToken.FIELD_NAME ) {
String name = parser.getText();
parser.nextToken(); // JsonToken.START_OBJECT
results.add(parser.readValueAs(classMap.get(name)));
}
// ASSERT: token = JsonToken.END_OBJECT
}
finally {
IOUtils.closeQuietly(in);
try {
parser.close();
}
catch( Exception e ) {}
}

Related

represent JSON file in a java program for querying values by key

I want to represent this file in my java program.
What I want to do is quickly search through it by "key" value, so for instance, given the value P26 I'd want to return spouse.
Maybe I can read it in as a HashMap using gson as I did with this program.
But what to do about this wonky structure:
{
"properties": {
"P6": "head of government",
"P7": "brother",
...
How could I fit that well into a HashMap? Is HashMap even the best choice?
I've sort of simplified it to this:
{
"P6": "head of government",
"P7": "brother",
"P9": "sister",
"P10": "video",
"P14": "highway marker",
"P15": "road map",
"P16": "highway system",
"P17": "country",
"P18": "image",
I've tried to use this code, but it outputs null
/*
* P values file
*/
String jsonTxt_P = null;
File P_Value_file = new File("properties-es.json");
//read in the P values
if (P_Value_file.exists())
{
InputStream is = new FileInputStream("properties-es.json");
jsonTxt_P = IOUtils.toString(is);
}
Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(jsonTxt_P, stringStringMap);
System.out.println(map);
It doesn't work because that file is not a Map<String, String>. it has a properties element, which contains a mapping, and a missing element, which contains an array. This mismatch will cause Json to return null, which is what you're seeing. Instead, try doing this:
public class MyData {
Map<String, String> properties;
List<String> missing;
}
And then, to deserialize, do:
MyData data = gson.fromJson(jsonTxt_P, MyData.class);
Map<String, String> stringStringMap = data.properties;
This will make the data structure match the structure of the json, and allow json to properly deserialize.

Is there a generic way of parsing Json in Java?

I have tried with gson and Jackson parsers unfortunately I couldn't achieve what I wanted to.
{
"rateName": "My Special Rate",
"adjustments": [
{
"adjustmentType": "LOAN_AMOUNT_GREATER_THAN_550K",
"rate": 0.75
},
{
"adjustmentType": "AMORTIZATION_TERM_LESS_THAN_30_YEARS",
"rate": -0.2
}
],
"errorTypes": [],
"premiumTaxs": [],
"renewalPremiums": [],
"totalInitialRate": 1.95,
"optimumPricing": false,
"miPricingVO": null,
"rateCardId": "BALS_NR",
"ratingInfoBaseRate": 1.4
}
Above is the Json I want to parse. I want to create generic methods using which I can access a value by name easily. For example:
getName(rateName) - Should return 'My Special Rate'
getNameFromArray(adjustmentType, adjustments) - Should return
'LOAN_AMOUNT_GREATER_THAN_550K'
Is there a way to do this? It should be generic so that this can be applied on any Json file.
Additional info: I tried using Gson, but this parses the whole file and throws an error if it finds an array.
JsonReader j = new JsonReader(new FileReader("Path of Json"));
j.beginObject();
while (j.hasNext()) {
String name = j.nextName();
if (name.equals("rateName")) {
System.out.println(j.nextString());
}
System.out.println(name);
}
I tried with jackson and encountered the same as Gson.
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createJsonParser("Path of Json");
while (jParser.nextToken() != JsonToken.END_OBJECT) {
System.out.println(jParser.getCurrentName());;
}
If you mean standard library when you say generic, then org.json would be that library.
Altough not as intuitive as GSON or Jackson, it is easy to use it:
JSONObject jsonData = new JSONObject(jsonString);
String rateName= jsonData.getString("rateName");//My Special Rate
To parse array you need to loop:
JSONArray adjustments = jsonData.getJSONArray("adjustments");
for(int i = 0; i < adjustments.length(); i++){
JSONObject adjustment = adjustments.getJSONObject(i);
String adjustmentType = adjustment.getString("adjustmentType");
}
Hi You can use JASON READER , it readers the JSON and map the data into a MAP .
Below is the URL to Download the JAR JASON READER.
https://drive.google.com/open?id=0BwyOcFBoJ5pueXdadFFMS2tjLVU
Below is the example -
package com;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.JasonReader;
public class Test {
public static void main(String[] args) {
String request ="{\"rateName\": \"My Special Rate\",\"adjustments\":[{\"adjustmentType\": \"LOAN_AMOUNT_GREATER_THAN_550K\",\"rate\": 0.75},{\"adjustmentType\": \"AMORTIZATION_TERM_LESS_THAN_30_YEARS\",\"rate\": -0.2}],\"errorTypes\": [],\"premiumTaxs\": [],\"renewalPremiums\": [],\"totalInitialRate\": 1.95,\"optimumPricing\": false,\"miPricingVO\": null,\"rateCardId\": \"BALS_NR\",\"ratingInfoBaseRate\": 1.}";
//
Map<String,String> map =new HashMap<String,String>();
map=JasonReader.readJason(request,map);
//System.out.println(map);
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+ "=" +entry.getValue());
}
}
}
OUTPUT -
rateCardId=BALS_NR
adjustments|rate1=-0.2
miPricingVO=null
adjustments|adjustmentType=LOAN_AMOUNT_GREATER_THAN_550K
adjustments|adjustmentType1=AMORTIZATION_TERM_LESS_THAN_30_YEARS
adjustments|rate=0.75
optimumPricing=false
totalInitialRate=1.95
rateName=My Special Rate
ratingInfoBaseRate=1.
You can use the standard JsonParser which is part of the javax.json package. This parser is part of Java EE since version 7 and you can use this parser without any additional library.
The parser allows you to navigate through a JSON structure using the so called 'pull parsing programming model'
JsonParser parser = Json.createParser(myJSON);
Event event = parser.next(); // START_OBJECT
event = parser.next(); // KEY_NAME
String key = parser.getString(); // 'rateName'
event = parser.next(); // STRING_VALUE
String value=parser.getString(); // 'My Special Rate'
event = parser.next(); // START_ARRAY
....
But of course you need to navigate through your json data structure
Or you can just use Jodd JSON parser. You just need to deserialize the input string and the result will be collected in regular Map and List.
JsonParser jsonParser = new JsonParser();
Map<String, Object> map = jsonParser.parse(input);
Simple as that - and the result is the most generic as it can be. Then just call map.get("rateName") to get your value and so on.
But notice that for adjustments you can get the way you want without some util method that would iterate elements and search for the right one. If you can, change the JSON so that you dont have an array of adjustments, but a map.
If you need specific results, just pass the type with the input string. See more about parsing features.

Get JSON key name using GSON

I have a JSON array which contains objects such as this:
{
"bjones": {
"fname": "Betty",
"lname": "Jones",
"password": "ababab",
"level": "manager"
}
}
my User class has a username which would require the JSON object's key to be used. How would I get the key of my JSON object?
What I have now is getting everything and creating a new User object, but leaving the username null. Which is understandable because my JSON object does not contain a key/value pair for "username":"value".
Gson gson = new Gson();
JsonParser p = new JsonParser();
JsonReader file = new JsonReader(new FileReader(this.filename));
JsonObject result = p.parse(file).getAsJsonObject().getAsJsonObject("bjones");
User newUser = gson.fromJson(result, User.class);
// newUser.username = null
// newUser.fname = "Betty"
// newUser.lname = "Jones"
// newUser.password = "ababab"
// newUser.level = "manager"
edit:
I'm trying to insert "bjones" into newUser.username with Gson, sorry for the lack of clarification
Use entrySet to get the keys. Loop through the entries and create a User for every key.
JsonObject result = p.parse(file).getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = result.entrySet();
for(Map.Entry<String, JsonElement> entry : entrySet) {
User newUser = gson.fromJson(p.getAsJsonObject(entry.getKey()), User.class);
newUser.username = entry.getKey();
//code...
}
Using keySet() directly excludes the necessity in iteration:
ArrayList<String> objectKeys =
new ArrayList<String>(
myJsonObject.keySet());
Your JSON is fairly simple, so even the manual sort of methods (like creating maps of strings etc for type) will work fine.
For complex JSONs(where there are many nested complex objects and lists of other complex objects inside your JSON), you can create POJO for your JSON with some tool like http://www.jsonschema2pojo.org/
And then just :
final Gson gson = new Gson();
final MyJsonModel obj = gson.fromJson(response, MyJsonModel.class);
// Just access your stuff in object. Example
System.out.println(obj.getResponse().getResults().get(0).getId());

Mapping between JSON formats in Java

I'm coming to Java from JavaScript/Ruby. Let's say I've got the following JSON object for an animal:
{
name: {
common: "Tiger",
latin: "Panthera tigris"
}
legs: 4
}
I'm dealing with lots of animal APIs, and I want to normalize them all into my own common format, like:
{
common_name: "Tiger",
latin_name: "Panthera tigris",
limbs: {
legs: 4,
arms: 0
}
}
In, say, JavaScript, this would be straightforward:
normalizeAnimal = function(original){
return {
common_name: original.name.common,
latin_name: original.name.latin,
limbs: {
legs: original.legs || 0,
arms: original.arms || 0
}
}
}
But what about in Java? Using the JSONObject class from org.json, I could go down the road of doing something like this:
public JSONObject normalizeAnimal(JSONObject original) throws JSONException{
JSONObject name = original.getJSONObject("name");
JSONObject limbs = new JSONObject();
JSONObject normalized = new JSONObject();
normalized.put("name_name", name.get("common"));
normalized.put("latin_name", name.get("latin"));
try{
limbs.put("legs", original.get("legs");
}catch(e){
limbs.put("legs", 0);
};
try{
limbs.put("arms", original.get("arms");
}catch(e){
limbs.put("arms", 0);
};
normalized.put("limbs", limbs);
return normalized;
}
This gets worse as the JSON objects I'm dealing with get longer and deeper. In addition to all of this, I'm dealing with many providers for animal objects and I'll eventually be looking to have some succinct configuration format for describing the transformations (like, maybe, "common_name": "name.common", "limbs.legs": "legs").
How would I go about making this suck less in Java?
Use a library like Gson or Jackson and map the JSON to a Java Object.
So you're going to have a bean like
public class JsonAnima {
private JsonName name;
private int legs;
}
public class JsonName {
private String commonName;
private String latinName;
}
which can be easily converted with any library with something like (with Jackson)
ObjectMapper mapper = new ObjectMapper();
JsonAnimal animal = mapper.readValue(jsonString, JsonAnimal.class);
then you can create a "converter" to map the JsonAnimal to you Animal class.
This can be a way of doing it. : )
Some links:
Gson: http://code.google.com/p/google-gson/
Jackson: http://wiki.fasterxml.com/JacksonHome
The pure Java solutions all are challenged to deal with unreliable structure of your source data. If you're running in a JVM, I recommend that you consider using Groovy to do the Parse and the Build of your source JSON. The result ends up looking a lot like the Javascript solution you outlined above:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def originals = [
'{ "name": { "common": "Tiger", "latin": "Panthera tigris" }, "legs": 4 }',
'{ "name": { "common": "Gecko", "latin": "Gek-onero" }, "legs": 4, "arms": 0 }',
'{ "name": { "common": "Liger" }, "legs": 4, "wings": 2 }',
'{ "name": { "common": "Human", "latin": "Homo Sapien" }, "legs": 2, "arms": 2 }'
]
originals.each { orig ->
def slurper = new JsonSlurper()
def parsed = slurper.parseText( orig )
def builder = new JsonBuilder()
// This builder looks a lot like the Javascript solution, no?
builder {
common_name parsed.name.common
latin_name parsed.name.latin
limbs {
legs parsed.legs ?: 0
arms parsed.arms ?: 0
}
}
def normalized = builder.toString()
println "$normalized"
}
Running the script above deals with "jagged" JSON (not all elements have the same attributes) and outputs like...
{"common_name":"Tiger","latin_name":"Panthera tigris","limbs":{"legs":4,"arms":0}}
{"common_name":"Gecko","latin_name":"Gek-onero","limbs":{"legs":4,"arms":0}}
{"common_name":"Liger","latin_name":null,"limbs":{"legs":4,"arms":0}}
{"common_name":"Human","latin_name":"Homo Sapien","limbs":{"legs":2,"arms":2}}
If you'll be using this for many different types of objects, I would suggest to use reflection instead of serializing each object manually. By using reflection you will not need to create methods like normalizeAnimal, you just create one method or one class to do the serialization to json format.
If you search for "mapping json java" you'll find some useful references. Like gson. Here is an example that is on their website:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
//(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
///==> json is {"value1":1,"value2":"abc"}
///Note that you can not serialize objects with circular references since that will result in infinite recursion.
//(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
//==> obj2 is just like obj
You can try little jmom java library
JsonValue json = JsonParser.parse(stringvariablewithjsoninside);
Jmom mom = Jmom.instance()
.copy("/name/common", "/common_name", true)
.copy("/name/latin", "/latin_name", true)
.copy("/arms", "/limbs/arms", true)
.copy("/legs", "/limbs/legs", true)
.remove("/name")
;
mom.apply(json);
String str = json.toPrettyString(" ");

How to convert hashmap to JSON object in Java

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
You can use:
new JSONObject(map);
Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html
Gson can also be used to serialize arbitrarily complex objects.
Here is how you use it:
Gson gson = new Gson();
String json = gson.toJson(myObject);
Gson will automatically convert collections to JSON arrays. Gson can serialize private fields and automatically ignores transient fields.
You can convert Map to JSON using Jackson as follows:
Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
Maven Dependencies for Jackson :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
If you are using `JSONObject` library, you can convert map to `JSON` as follows:
JSONObject Library:
import org.json.JSONObject;
Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
JSONObject json = new JSONObject(map);
System.out.println(json);
Maven Dependencies for `JSONObject` :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
Hope this will help. Happy coding.
Example using json
Map<String, Object> data = new HashMap<String, Object>();
data.put( "name", "Mars" );
data.put( "age", 32 );
data.put( "city", "NY" );
JSONObject json = new JSONObject();
json.putAll( data );
System.out.printf( "JSON: %s", json.toString(2) );
output::
JSON: {
"age": 32,
"name": "Mars",
"city": "NY"
}
You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation.
http://code.google.com/p/google-gson/
You can just enumerate the map and add the key-value pairs to the JSONObject
Method :
private JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
JSONObject jsonData = new JSONObject();
for (String key : map.keySet()) {
Object value = map.get(key);
if (value instanceof Map<?, ?>) {
value = getJsonFromMap((Map<String, Object>) value);
}
jsonData.put(key, value);
}
return jsonData;
}
In my case I didn't want any dependancies. Using Java 8 you can get JSON as a string this simple:
Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
.map(e -> "\""+ e.getKey() + "\":\"" + String.valueOf(e.getValue()) + "\"")
.collect(Collectors.joining(", "))+"}";
Underscore-java library can convert hash map or array list to json and vice verse.
import com.github.underscore.U;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("1", "a");
map.put("2", "b");
System.out.println(U.toJson(map));
// {
// "1": "a",
// "2": "b"
// }
}
}
Late to the party but here is my GSON adhoc writer for serializing hashmap. I had to write map of key-value pairs as json string attributes, expect one specific to be integer type. I did not want to create custom JavaBean wrapper for this simple usecase.
GSON JsonWriter class is easy to use serializer class containing few strongly typed writer.value() functions.
// write Map as JSON document to http servlet response
Map<String,String> sd = DAO.getSD(123);
res.setContentType("application/json; charset=UTF-8");
res.setCharacterEncoding("UTF-8");
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginObject();
for(String key : sd.keySet()) {
String val = sd.get(key);
writer.name(key);
if (key.equals("UniqueID") && val!=null)
writer.value(Long.parseLong(val));
else
writer.value(val);
}
writer.endObject();
writer.close();
If none of the custom types be needed I could have just use toJson() function. gson-2.2.4.jar library is just under 190KB without any brutal dependencies. Easy to use on any custom servlet app or standalone application without big framework integrations.
Gson gson = new Gson();
String json = gson.toJson(myMap);
If you need use it in the code.
Gson gsone = new Gson();
JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();
This is typically the work of a Json library, you should not try to do it yourself. All json libraries should implement what you are asking for, and you can
find a list of Java Json libraries on json.org, at the bottom of the page.
This solution works with complex JSONs:
public Object toJSON(Object object) throws JSONException {
if (object instanceof HashMap) {
JSONObject json = new JSONObject();
HashMap map = (HashMap) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable) object)) {
json.put(toJSON(value));
}
return json;
}
else {
return object;
}
}
Better be late than never. I used GSON to convert list of HashMap to string if in case you want to have a serialized list.
List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);
String json = new Gson().toJson(list);
This json produces [{"key":"value","key":"value","key":"value"}]
Here my single-line solution with GSON:
myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);
For those using org.json.simple.JSONObject, you could convert the map to Json String and parse it to get the JSONObject.
JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));
I found another way to handle it.
Map obj=new HashMap();
obj.put("name","sonoo");
obj.put("age",new Integer(27));
obj.put("salary",new Double(600000));
String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);
Hope this helps.
Thanks.
If you don't really need HashMap then you can do something like that:
String jsonString = new JSONObject() {{
put("firstName", user.firstName);
put("lastName", user.lastName);
}}.toString();
Output:
{
"firstName": "John",
"lastName": "Doe"
}
we use Gson.
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);
If you are using net.sf.json.JSONObject then you won't find a JSONObject(map) constructor in it. You have to use the public static JSONObject fromObject( Object object ) method. This method accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.
JSONObject jsonObject = JSONObject.fromObject(myMap);
No need for Gson or JSON parsing libraries.
Just using new JSONObject(Map<String, JSONObject>).toString(), e.g:
/**
* convert target map to JSON string
*
* #param map the target map
* #return JSON string of the map
*/
#NonNull public String toJson(#NonNull Map<String, Target> map) {
final Map<String, JSONObject> flatMap = new HashMap<>();
for (String key : map.keySet()) {
try {
flatMap.put(key, toJsonObject(map.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
// 2 indentSpaces for pretty printing
return new JSONObject(flatMap).toString(2);
} catch (JSONException e) {
e.printStackTrace();
return "{}";
}
}
I'm using Alibaba fastjson, easy and simple:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>VERSION_CODE</version>
</dependency>
and import:
import com.alibaba.fastjson.JSON;
Then:
String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize
Everything is ok.
If you are using JSR 374: Java API for JSON Processing ( javax json )
This seems to do the trick:
JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
JsonObject jsonObject = job.build();
Gson way for a bit more complex maps and lists using TypeToken.getParameterized method:
We have a map that looks like this:
Map<Long, List<NewFile>> map;
We get the Type using the above mentioned getParameterized method like this:
Type listOfNewFiles = TypeToken.getParameterized(ArrayList.class, NewFile.class).getType();
Type mapOfList = TypeToken.getParameterized(LinkedHashMap.class, Long.class, listOfNewFiles).getType();
And then use the Gson object fromJson method like this using the mapOfList object like this:
Map<Long, List<NewFile>> map = new Gson().fromJson(fileContent, mapOfList);
The mentioned object NewFile looks like this:
class NewFile
{
private long id;
private String fileName;
public void setId(final long id)
{
this.id = id;
}
public void setFileName(final String fileName)
{
this.fileName = fileName;
}
}
The deserialized JSON looks like this:
{
"1": [
{
"id": 12232,
"fileName": "test.html"
},
{
"id": 12233,
"fileName": "file.txt"
},
{
"id": 12234,
"fileName": "obj.json"
}
],
"2": [
{
"id": 122321,
"fileName": "test2.html"
},
{
"id": 122332,
"fileName": "file2.txt"
},
{
"id": 122343,
"fileName": "obj2.json"
}
]
}
You can use XStream - it is really handy. See the examples here
package com.thoughtworks.xstream.json.test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class WriteTest {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<String,String>();
map.add("1", "a");
map.add("2", "b");
XStream xstream = new XStream(new JettisonMappedXmlDriver());
System.out.println(xstream.toXML(map));
}
}
If you use complex objects, you should apply enableComplexMapKeySerialization(), as stated in https://stackoverflow.com/a/24635655/2914140 and https://stackoverflow.com/a/26374888/2914140.
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<Point, String> original = new LinkedHashMap<Point, String>();
original.put(new Point(5, 6), "a");
original.put(new Point(8, 8), "b");
System.out.println(gson.toJson(original));
Output will be:
{
"(5,6)": "a",
"(8,8)": "b"
}
import org.json.JSONObject;
HashMap<Object, Object> map = new HashMap<>();
String[] list={"Grader","Participant"};
String[] list1={"Assistant","intern"};
map.put("TeachingAssistant",list);
map.put("Writer",list1);
JSONObject jsonObject = new JSONObject(map);
System.out.printf(jsonObject.toString());
// Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}
You can use Gson.
This library provides simple methods to convert Java objects to JSON objects and vice-versa.
Example:
GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);
You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.
However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).
More information about Gson here.
Remember that the object must implement the Serializable interface.
this works for me :
import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")
println new JsonBuilder(properties).toPrettyString()
I faced a similar problem when deserializing the Response from custom commands in selenium. The response was json, but selenium internally translates that into a java.util.HashMap[String, Object]
If you are familiar with scala and use the play-API for JSON, you might benefit from this:
import play.api.libs.json.{JsValue, Json}
import scala.collection.JavaConversions.mapAsScalaMap
object JsonParser {
def parse(map: Map[String, Any]): JsValue = {
val values = for((key, value) <- map) yield {
value match {
case m: java.util.Map[String, _] #unchecked => Json.obj(key -> parse(m.toMap))
case m: Map[String, _] #unchecked => Json.obj(key -> parse(m))
case int: Int => Json.obj(key -> int)
case str: String => Json.obj(key -> str)
case bool: Boolean => Json.obj(key -> bool)
}
}
values.foldLeft(Json.obj())((temp, obj) => {
temp.deepMerge(obj)
})
}
}
Small code description:
The code recursively traverses through the HashMap until basic types (String, Integer, Boolean) are found. These basic types can be directly wrapped into a JsObject. When the recursion is unfolded, the deepmerge concatenates the created objects.
'#unchecked' takes care of type erasure warnings.
First convert all your objects into valid Strings
HashMap<String, String> params = new HashMap<>();
params.put("arg1", "<b>some text</b>");
params.put("arg2", someObject.toString());
Then insert the entire map into a org.json.JSONObject
JSONObject postData = new JSONObject(params);
Now you can get the JSON by simply calling the object's toString
postData.toString()
//{"arg1":"<b>some text<\/b>" "arg2":"object output"}
Create a new JSONObject
JSONObject o = new JSONObject(postData.toString());
Or as a byte array for sending over HTTP
postData.toString().getBytes("UTF-8");

Categories