Rename map keys in GSON according to FieldNamingPolicy - java

Say I'm building my GSON object like this
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
and now I want to deserialize the following JSON
{
"MyMap" : {
"Key1" : "Foo",
"Key2" : "Bar"
}
}
into the following class (which is working just fine)
public class MapClass {
Map<String,String> myMap;
}
but I also would like the keys to be named "key1" and "key2". How would I go about this?

You can try in this way:
try {
JSONObject jObj = new JSONObject("{"
+ " \"MyMap\" : {"
+ " \"Key1\" : \"Foo\","
+ " \"Key2\" : \"Bar\""
+ " }"
+ "}"); // this parses the json
JSONObject jObjt = jObj.getJSONObject("MyMap");
//old version with out GSON
Map<String, String> map = new HashMap();
Iterator itr = jObjt.keys();
while (itr.hasNext()) {
String key = (String) itr.next();
String value = jObjt.getString(key);
map.put(key, value);
}
//desalinized one with GSON
Map<String, String> map1 = new Gson().fromJson(jObjt.toString(), HashMap.class);
for (String str : map1.keySet()) {
System.out.println("k:" + str + " v:" + map1.get(str));
}
} catch (JSONException ex) {
//log the error
}

FieldNamingPolicy is applied to fields of json value. It is not possible to apply this to maps' keys (a map which has key, value pairs) at json.
Easy solution:
After deserialization, iterate over your map and rename key names. i.e. Key1 to key1 and Key2 to key2.
Other solution:
Write a custom TypeAdapter which handles deserialization process and renames keys.
public class MapClassTypeAdapter extends TypeAdapter<MapClass> {
#Override
public MapClass read(JsonReader in) throws IOException {
final MapClass mapClassInstance = new MapClass();
mapClassInstance.myMap = new HashMap<String, String>();
in.beginObject();
if("myMap".equalsIgnoreCase(in.nextName())) {
in.beginObject();
while (in.hasNext()) {
String key = in.nextName();
// You want keys as camel case
String newKey = key.substring(0,1).toLowerCase() + key.substring(1);
String value = in.nextString();
mapClassInstance.myMap.put(newKey, value);
}
in.endObject();
}
in.endObject();
return mapClassInstance;
}
#Override
public void write(JsonWriter out, MapClass mapClass) throws IOException {
throw new RuntimeException("MapClassTypeAdapter.write method not implemented yet!");
}
}
Test Other solution:
String json = "{\"myMap\":{\"Key1\":\"Foo\",\"Key2\":\"Bar\"}}";
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MapClass.class, new MapClassTypeAdapter());
final Gson gson = gsonBuilder.create();
MapClass mapClass = gson.fromJson(json, MapClass.class);

Related

Jackson map deserialization - value replacement

What's the best way to deserialize this Json object?
{
"key1" : "val1",
"key2" : "blank"
}
into a java hashmap, where the string blank is replaced with null?
{
"key1" : "val1",
"key2" : null
}
I am currently using Jackson for deserialization.
You will find part of the answer here.
You just need to manipulate the line inside the while loop:
Object value;
if (object.get(key).equals("blank")) {
value = "null";
} else {
value = object.get(key);
}
and make print out will give:
System.out.println(map.get("key1")); // returns val1
System.out.println(map.get("key2")); // returns null
You final code will look like this, and you might need to import the proper .jar files:
import com.orsoncharts.util.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static com.sun.xml.internal.ws.binding.WebServiceFeatureList.toList;
public class JsonAnswerOne {
public static void main(String[] args) throws JSONException {
String input = "{\n" +
" \"key1\" : \"val1\",\n" +
" \"key2\" : \"blank\"\n" +
"}";
parse(input);
}
private static void parse(String input) throws JSONException {
JSONObject mainObject = new JSONObject(input);
Map<String, Object> map = jsonToMap(mainObject);
System.out.println(map.get("key1")); // returns val1
System.out.println(map.get("key2")); // returns null
}
private static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if (json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
Object value;
if (object.get(key).equals("blank")) {
value = "null";
} else {
value = object.get(key);
}
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
}
I tried this and ended up with this:
// use of the deserializer
String json = "{\"key1\":\"val1\",\"key2\":\"blank\"}";
ObjectMapper mapperMap = new ObjectMapper();
SimpleModule moduleMap = new SimpleModule();
moduleMap.addDeserializer(Map.class, new MapDeserializer());
mapperMap.registerModule(moduleMap);
Map map = mapperMap.readValue(json, Map.class);
// custom deserializer
public class MapDeserializer extends StdDeserializer<Map<String, String>> {
public MapDeserializer() {
this(null);
}
public MapDeserializer(Class<?> vc) {
super(vc);
}
#Override
public Map<String, String> deserialize(JsonParser jp, DeserializationContext context)
throws IOException {
// definitely not the best way but it works...
Map<String, String> map = new HashMap<>();
String[] keys = new String[] {"key1", "key2"};
JsonNode node = jp.getCodec().readTree(jp);
String value;
for (String key : keys) {
value = node.get(key).asText();
if (value.equals("blank")) {
value = null;
}
map.put(key, value);
}
return map;
}
}
Full example solution with an additional example to deserialize the JSON into another class:
https://gist.github.com/audacus/e70ce0f3cd4b17197d911769e05b237e

How can I store key-value pairs in JSON to be deserialized in Java?

I have data in JSON like so:
{
"foo": "bar",
"key": true,
"otherKey": 10
}
The key is a String and the value is a primitive (int, float, double, long, etc.) or a String. I want a simple, cast-free wrapper for each of the above.
Here's my wrapper class:
public final class Wrapper<T> {
private String key;
private T value;
}
If I specified Wrapper[] wrappedValues in an object to be deserialized, could I (using Jackson or GSON) deserialize the map to a list of the wrapper?
Thanks for any replies!
First of all, the input you specified can never be deserialized into an array or collection because it isn't one. a json collection of pairs of key-value looks like this
[
{"foo": "bar"},
{"key": true},
{"otherKey": 10}
]
and it can be deserialized into a collection of Wrappers if you make the class like this
public class Wrapper<T> {
private String key;
private T value;
#JsonAnySetter
public void set(String key, Object value) {
this.key = key;
this.value = (T)value;
}
public String toString() { // just for nice printing
return key + "=" + value.toString();
}
}
and then you have to tell Jackson what is the generic type of the collection that will host the deserialized json:
public static void main(String[] args)
{
String str = "[ {\"foo\": \"bar\"}, {\"key\": true}, {\"otherKey\": 10} ]";
try (InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"))) {
ObjectMapper objectMapper = new ObjectMapper();
JavaType listWrappersType = objectMapper.getTypeFactory()
.constructCollectionType(List.class, Wrapper.class);
List<Wrapper> list = objectMapper.readValue(is, listWrappersType);
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
output:
[foo=bar, key=true, otherKey=10]
If you just want to load pairs of key-value and not worry about type of value, then with Jackson you can load it all into Map<String, ?>
public static void main(String[] args)
{
String str = "{ \"foo\": \"bar\", \"key\": true, \"otherKey\": 10 }";
try (InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"))) {
Map<String, ?> map = new ObjectMapper().readValue(is, Map.class);
// print map contents
System.out.println(map);
// print type of map values
System.out.print(entry.getKey() + "=" + entry.getValue().getClass()+ ", "));
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
output
{foo=bar, key=true, otherKey=10}
foo=class java.lang.String, key=class java.lang.Boolean, otherKey=class java.lang.Integer,

Copy filtered JSON data from one file to another using gson library in java

I want to copy JSON fields from one file to another but only after the field satisfies a particular condition, as for example
{"dataset":
[
{"album_id":1,
"album_type":"Live Performance",
"artist_name":"John Doe",....
}
]
}
I want to copy only those records which have a user given artist_name or any other property, else skip the tuple for copying. I am using the following code to add the filtered records to a JSONObject "wr" which I then write to my output file. But its not giving me the desired results
public static void dumpJSONElement(JsonElement element) {
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
java.util.Set<java.util.Map.Entry<String,JsonElement>> entries = obj.entrySet();
java.util.Iterator<java.util.Map.Entry<String,JsonElement>> iter = entries.iterator();
while (iter.hasNext()) {
java.util.Map.Entry<String,JsonElement> entry = iter.next();
if(entry.getKey().equals(filterKey)){
if(! entry.getValue().toString().replace("\"", "").equals(filterValue)){
wr.put(entry.getKey(), entry.getValue());
}
}
else{
wr.put(entry.getKey(), entry.getValue());
}
dumpJSONElement(entry.getValue());
}
} else if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
java.util.Iterator<JsonElement> iter = array.iterator();
while (iter.hasNext()) {
JsonElement entry = iter.next();
dumpJSONElement(entry);
}
} else if (element.isJsonPrimitive()) {
JsonPrimitive value = element.getAsJsonPrimitive();
} else if (element.isJsonNull()) {
} else {
System.out.println("Error. Unknown type of element");
}
}
use code below code to convert your json string to generic java type List<Map<Object, Object>>, use code below.
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Test {
public static void main(String... args) {
String str = "[{'id':1,'name':'yogesh'},{'id':2,'name':'aarush', 'degree': 'MCA'}]";
Type type = new TypeToken<List<Map<Object, Object>>>() {
}.getType();
List<Map<Object, Object>> list = new Gson().fromJson(str, type);
System.out.println(new Gson().toJson(list));
filterList(list, "name", "yogesh");
System.out.println(new Gson().toJson(list));
}
public static void filterList(List<Map<Object, Object>> list, String key, Object value) {
for (Map<Object, Object> map : list) {
if (map.containsKey(key)) {
if (map.get(key).equals(value)) {
list.remove(map);
}
}
}
}
}
here i filterd name=yogesh record.
output:
[{"id":1.0,"name":"yogesh"},{"id":2.0,"name":"aarush","degree":"MCA"}]
[{"id":2.0,"name":"aarush","degree":"MCA"}]
I had similar issues and I googled, read a lot about this. In conclusion, the best(most efficient) way (with gson) is to write a custom TypeAdapter for your case.
You can test sample code below (it is working as you expected):
public static void answer() {
String jsonAsText = "{\"dataset\":[{\"album_id\":1,\"album_type\":\"Live Performance\",\"artist_name\":\"John Doe\"},{\"album_id\":2,\"album_type\":\"A Dummy Performance\"}]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(List.class, new AlbumInfoListTypeAdapter());
Gson gson = gsonBuilder.create();
List<AlbumInfo> dataSet = gson.fromJson(jsonAsText, List.class);
System.out.println(gson.toJson(dataSet));
}
private static class AlbumInfo {
int album_id;
String album_type;
String artist_name;
}
private static class AlbumInfoListTypeAdapter extends
TypeAdapter<List<AlbumInfo>> {
#Override
public List<AlbumInfo> read(com.google.gson.stream.JsonReader in)
throws IOException {
List<AlbumInfo> dataSet = new ArrayList<AlbumInfo>();
in.beginObject();
while (in.hasNext()) {
if ("dataset".equals(in.nextName())) {
in.beginArray();
while (in.hasNext()) {
in.beginObject();
AlbumInfo albumInfo = new AlbumInfo();
while (in.hasNext()) {
String jsonTag = in.nextName();
if ("album_id".equals(jsonTag)) {
albumInfo.album_id = in.nextInt();
} else if ("album_type".equals(jsonTag)) {
albumInfo.album_type = in.nextString();
} else if ("artist_name".equals(jsonTag)) {
albumInfo.artist_name = in.nextString();
}
}
in.endObject();
if (albumInfo.artist_name != null && !"".equals(albumInfo.artist_name.trim())) {
dataSet.add(albumInfo);
} else {
System.out.println("Album info ignored because it has no artist_name value");
}
}
in.endArray();
}
}
in.endObject();
return dataSet;
}
#Override
public void write(com.google.gson.stream.JsonWriter out,
List<AlbumInfo> dataSet) throws IOException {
out.beginObject();
out.name("dataset").beginArray();
for (final AlbumInfo albumInfo : dataSet) {
out.beginObject();
out.name("album_id").value(albumInfo.album_id);
out.name("album_type").value(albumInfo.album_type);
out.name("artist_name").value(albumInfo.artist_name);
out.endObject();
}
out.endArray();
out.endObject();
}
}
You can modify the read and the write methods. Gson has many cool functions. I strongly suggest you to read samples at this link.
Edit:
Incoming json text:
{
"dataset": [
{
"album_id": 1,
"album_type": "Live Performance",
"artist_name": "John Doe"
},
{
"album_id": 2,
"album_type": "A Dummy Performance"
}
]
}
The output at System.out.println at answer method:
[
{
"artist_name": "John Doe",
"album_type": "Live Performance",
"album_id": 1
}
]

How to Read Json File Without Giving Element Names in Java

I want to read json file as follow;
{
"M": {
"row": [
{
"col1": "c00"
},
{
"col1": "c10",
"col2": "c11"
},
{
"col1": "c20",
"col2": "c21",
"col3": "c22"
}
]
}
}
Next to reading, I want to print "c00","c10","c11","c20","c21","c22" but without giving element as "col1","col2","col3"...
Thanks for helping.
You can use org.json library for this. It is here. General idea:
JSONObject obj = new JSONObject(sourceString);
for(String key : obj.keys()){
String value = obj.getString(key);
// Process value here
}
Use any JSON parsing library such as GSON or Jackson and convert it into Java Object.
Sample code using GSON library
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(jsonString, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
// get the desired value from map
Map<String,ArrayList<Map<String,String>>> mMap=(Map<String,ArrayList<Map<String,String>>>)data.get("M");
ArrayList<Map<String,String>> rowArray=mMap.get("row");
for(Map<String,String> colMap:rowArray){
for(String value:colMap.values()){
System.out.println(value);
}
}
You can convert JSON string into Java POJO class as well that is replica of the JSON string
class MDetails {
private MDetail M;
// getter & setter
}
class MDetail {
private ArrayList<Map<String, String>> row;
// getter & setter
}
...
MDetails data = new Gson().fromJson(jsonString, MDetails.class);
for (Map<String, String> colMap : data.getM().getRow()) {
for (String value : colMap.values()) {
System.out.println(value);
}
}
You can use different field name using #SerializedName annotation.
class MDetails {
#SerializedName("M")
private MDetail mDetail;
// getter & setter
}
As per comments, the keys are dynamic so iterate the map containing another map in it and print all the values whose key starts with col
sample code: (call below method that recursively iterate all keys and values)
public static void printColValues(Object data) {
if (data instanceof Map) {
for (Map.Entry<String, Object> entry : ((Map<String, Object>) data).entrySet()) {
String key = entry.getKey();
if (key.startsWith("col")) {
System.out.println(entry.getValue());
} else {
printColValues(entry.getValue());
}
}
} else if (data instanceof List) {
for (Object obj : (List) data) {
printColValues(obj);
}
}
}
output:
c00
c10
c11
c20
c21
c22
OR if nothing works then try with regex pattern but keep it as last resort
("col\d+":)("[^"]*")
Here is online demo
Or try with Reluctant Qualifier
("col\d+":)(".*?")
Here is demo
sample code:
String jsonString = "{\"M\":{\"row\":[{\"col1\":\"c00\"},{\"col1\":\"c10\",\"col2\":\"c11\"},{\"col1\":\"c20\",\"col2\":\"c21\",\"col3\":\"c22\"}]}}";
Pattern p = Pattern.compile("(\"col\\d+\":)(\"[^\"]*\")");
Matcher m = p.matcher(jsonString);
while (m.find()) {
System.out.println(m.group(2));
}
output:
"c00"
"c10"
"c11"
"c20"
"c21"
"c22"
Code updated to print all values regardless of keys
public static void printColValues(Object data) {
if (data instanceof Map) {
for (Map.Entry<String, Object> entry : ((Map<String, Object>) data).entrySet()) {
Object value=entry.getValue();
if (value instanceof String) {
System.out.println(value);
} else {
printColValues(value);
}
}
} else if (data instanceof List) {
for (Object obj : (List) data) {
printColValues(obj);
}
}
}

Convert a JSON String to a HashMap

I'm using Java, and I have a String which is JSON:
{
"name" : "abc" ,
"email id " : ["abc#gmail.com","def#gmail.com","ghi#gmail.com"]
}
Then my Map in Java:
Map<String, Object> retMap = new HashMap<String, Object>();
I want to store all the data from the JSONObject in that HashMap.
Can anyone provide code for this? I want to use the org.json library.
In recursive way:
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Using Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
Using Gson, you can do the following:
Map<String, Object> retMap = new Gson().fromJson(
jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
Hope this will work, try this:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);
str, your JSON String
As Simple as this, if you want emailid,
String emailIds = response.get("email id").toString();
I just used Gson
HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);
Here is Vikas's code ported to JSR 353:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;
public class JsonUtils {
public static Map<String, Object> jsonToMap(JsonObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JsonObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JsonObject object) throws JsonException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keySet().iterator();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JsonArray) {
value = toList((JsonArray) value);
}
else if(value instanceof JsonObject) {
value = toMap((JsonObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JsonArray array) {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.size(); i++) {
Object value = array.get(i);
if(value instanceof JsonArray) {
value = toList((JsonArray) value);
}
else if(value instanceof JsonObject) {
value = toMap((JsonObject) value);
}
list.add(value);
}
return list;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonUtils {
public static Map<String, Object> jsonToMap(JSONObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != null) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keySet().iterator();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.size(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
try this code :
Map<String, String> params = new HashMap<String, String>();
try
{
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = (String) keys.next();
String value = jsonObject.getString(key);
params.put(key, value);
}
}
catch (Exception xx)
{
xx.toString();
}
Latest Update: I have used FasterXML Jackson Databind2.12.3 to Convert JSON string to Map, Map to JSON string.
// javax.ws.rs.core.Response clientresponse = null; // Read JSON with Jersey 2.0 (JAX-RS 2.0)
// String json_string = clientresponse.readEntity(String.class);
String json_string = "[\r\n"
+ "{\"domain\":\"stackoverflow.com\", \"userId\":5081877, \"userName\":\"Yash\"},\r\n"
+ "{\"domain\":\"stackoverflow.com\", \"userId\":6575754, \"userName\":\"Yash\"}\r\n"
+ "]";
System.out.println("Input/Response JSON string:"+json_string);
ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
//java.util.Map<String, String> map = mapper.readValue(json_string, java.util.Map.class);
List<Map<String, Object>> listOfMaps = mapper.readValue(json_string, new com.fasterxml.jackson.core.type.TypeReference< List<Map<String, Object>>>() {});
System.out.println("fasterxml JSON string to List of Map:"+listOfMaps);
String json = mapper.writeValueAsString(listOfMaps);
System.out.println("fasterxml List of Map to JSON string:[compact-print]"+json);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(listOfMaps);
System.out.println("fasterxml List of Map to JSON string:[pretty-print]"+json);
output:
Input/Response JSON string:[
{"domain":"stackoverflow.com", "userId":5081877, "userName":"Yash"},
{"domain":"stackoverflow.com", "userId":6575754, "userName":"Yash"}
]
fasterxml JSON string to List of Map:[{domain=stackoverflow.com, userId=5081877, userName=Yash}, {domain=stackoverflow.com, userId=6575754, userName=Yash}]
fasterxml List of Map to JSON string:[compact-print][{"domain":"stackoverflow.com","userId":5081877,"userName":"Yash"},{"domain":"stackoverflow.com","userId":6575754,"userName":"Yash"}]
fasterxml List of Map to JSON string:[pretty-print][ {
"domain" : "stackoverflow.com",
"userId" : 5081877,
"userName" : "Yash"
}, {
"domain" : "stackoverflow.com",
"userId" : 6575754,
"userName" : "Yash"
} ]
Converting a JSON String to Map
public static java.util.Map<String, Object> jsonString2Map( String jsonString ) throws org.json.JSONException {
Map<String, Object> keys = new HashMap<String, Object>();
org.json.JSONObject jsonObject = new org.json.JSONObject( jsonString ); // HashMap
java.util.Iterator<?> keyset = jsonObject.keys(); // HM
while (keyset.hasNext()) {
String key = (String) keyset.next();
Object value = jsonObject.get(key);
System.out.print("\n Key : "+key);
if ( value instanceof org.json.JSONObject ) {
System.out.println("Incomin value is of JSONObject : ");
keys.put( key, jsonString2Map( value.toString() ));
} else if ( value instanceof org.json.JSONArray) {
org.json.JSONArray jsonArray = jsonObject.getJSONArray(key);
//JSONArray jsonArray = new JSONArray(value.toString());
keys.put( key, jsonArray2List( jsonArray ));
} else {
keyNode( value);
keys.put( key, value );
}
}
return keys;
}
Converting JSON Array to List
public static java.util.List<Object> jsonArray2List( org.json.JSONArray arrayOFKeys ) throws org.json.JSONException {
System.out.println("Incoming value is of JSONArray : =========");
java.util.List<Object> array2List = new java.util.ArrayList<Object>();
for ( int i = 0; i < arrayOFKeys.length(); i++ ) {
if ( arrayOFKeys.opt(i) instanceof org.json.JSONObject ) {
Map<String, Object> subObj2Map = jsonString2Map(arrayOFKeys.opt(i).toString());
array2List.add(subObj2Map);
} else if ( arrayOFKeys.opt(i) instanceof org.json.JSONArray ) {
java.util.List<Object> subarray2List = jsonArray2List((org.json.JSONArray) arrayOFKeys.opt(i));
array2List.add(subarray2List);
} else {
keyNode( arrayOFKeys.opt(i) );
array2List.add( arrayOFKeys.opt(i) );
}
}
return array2List;
}
public static Object keyNode(Object o) {
if (o instanceof String || o instanceof Character) return (String) o;
else if (o instanceof Number) return (Number) o;
else return o;
}
Display JSON of Any Format
public static void displayJSONMAP( Map<String, Object> allKeys ) throws Exception{
Set<String> keyset = allKeys.keySet(); // HM$keyset
if (! keyset.isEmpty()) {
Iterator<String> keys = keyset.iterator(); // HM$keysIterator
while (keys.hasNext()) {
String key = keys.next();
Object value = allKeys.get( key );
if ( value instanceof Map ) {
System.out.println("\n Object Key : "+key);
displayJSONMAP(jsonString2Map(value.toString()));
}else if ( value instanceof List ) {
System.out.println("\n Array Key : "+key);
JSONArray jsonArray = new JSONArray(value.toString());
jsonArray2List(jsonArray);
}else {
System.out.println("key : "+key+" value : "+value);
}
}
}
}
Google.gson to HashMap.
Convert using Jackson :
JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);
Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});
You can convert any JSON to map by using Jackson library as below:
String json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"abc#gmail.com\",\"def#gmail.com\",\"ghi#gmail.com\"]\r\n}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
System.out.println(map);
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>
Hope this will help. Happy coding :)
You can use Jackson API as well for this :
final String json = "....your json...";
final ObjectMapper mapper = new ObjectMapper();
final MapType type = mapper.getTypeFactory().constructMapType(
Map.class, String.class, Object.class);
final Map<String, Object> data = mapper.readValue(json, type);
If you hate recursion - using a Stack and javax.json to convert a Json String into a List of Maps:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.json.Json;
import javax.json.stream.JsonParser;
public class TestCreateObjFromJson {
public static List<Map<String,Object>> extract(InputStream is) {
List extracted = new ArrayList<>();
JsonParser parser = Json.createParser(is);
String nextKey = "";
Object nextval = "";
Stack s = new Stack<>();
while(parser.hasNext()) {
JsonParser.Event event = parser.next();
switch(event) {
case START_ARRAY : List nextList = new ArrayList<>();
if(!s.empty()) {
// If this is not the root object, add it to tbe parent object
setValue(s,nextKey,nextList);
}
s.push(nextList);
break;
case START_OBJECT : Map<String,Object> nextMap = new HashMap<>();
if(!s.empty()) {
// If this is not the root object, add it to tbe parent object
setValue(s,nextKey,nextMap);
}
s.push(nextMap);
break;
case KEY_NAME : nextKey = parser.getString();
break;
case VALUE_STRING : setValue(s,nextKey,parser.getString());
break;
case VALUE_NUMBER : setValue(s,nextKey,parser.getLong());
break;
case VALUE_TRUE : setValue(s,nextKey,true);
break;
case VALUE_FALSE : setValue(s,nextKey,false);
break;
case VALUE_NULL : setValue(s,nextKey,"");
break;
case END_OBJECT :
case END_ARRAY : if(s.size() > 1) {
// If this is not a root object, move up
s.pop();
} else {
// If this is a root object, add ir ro rhw final
extracted.add(s.pop());
}
default : break;
}
}
return extracted;
}
private static void setValue(Stack s, String nextKey, Object v) {
if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
else ((List)s.peek()).add(v);
}
}
There’s an older answer using javax.json posted here, however it only converts JsonArray and JsonObject, but there are still JsonString, JsonNumber, and JsonValue wrapper classes in the output. If you want to get rid of these, here’s my solution which will unwrap everything.
Beside that, it makes use of Java 8 streams and is contained in a single method.
/**
* Convert a JsonValue into a “plain” Java structure (using Map and List).
*
* #param value The JsonValue, not <code>null</code>.
* #return Map, List, String, Number, Boolean, or <code>null</code>.
*/
public static Object toObject(JsonValue value) {
Objects.requireNonNull(value, "value was null");
switch (value.getValueType()) {
case ARRAY:
return ((JsonArray) value)
.stream()
.map(JsonUtils::toObject)
.collect(Collectors.toList());
case OBJECT:
return ((JsonObject) value)
.entrySet()
.stream()
.collect(Collectors.toMap(
Entry::getKey,
e -> toObject(e.getValue())));
case STRING:
return ((JsonString) value).getString();
case NUMBER:
return ((JsonNumber) value).numberValue();
case TRUE:
return Boolean.TRUE;
case FALSE:
return Boolean.FALSE;
case NULL:
return null;
default:
throw new IllegalArgumentException("Unexpected type: " + value.getValueType());
}
}
You can use google gson library to convert json object.
https://code.google.com/p/google-gson/‎
Other librarys like Jackson are also available.
This won't convert it to a map. But you can do all things which you want.
Brief and Useful:
/**
* #param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
* a <code>Boolean</code>, a <code>Number</code>,
* a <code>null</code> or a <code>JSONObject.NULL</code>.
* #return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
* a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
*/
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
if (jsonThing instanceof JSONArray) {
final ArrayList<Object> list = new ArrayList<>();
final JSONArray jsonArray = (JSONArray) jsonThing;
final int l = jsonArray.length();
for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i)));
return list;
}
if (jsonThing instanceof JSONObject) {
final HashMap<String, Object> map = new HashMap<>();
final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
while (keysItr.hasNext()) {
final String key = keysItr.next();
map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
}
return map;
}
if (JSONObject.NULL.equals(jsonThing)) return null;
return jsonThing;
}
Thank #Vikas Gupta.
The following parser reads a file, parses it into a generic JsonElement, using Google's JsonParser.parse method, and then converts all the items in the generated JSON into a native Java List<object> or Map<String, Object>.
Note: The code below is based off of Vikas Gupta's answer.
GsonParser.java
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
public class GsonParser {
public static void main(String[] args) {
try {
print(loadJsonArray("data_array.json", true));
print(loadJsonObject("data_object.json", true));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void print(Object object) {
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object).toString());
}
public static Map<String, Object> loadJsonObject(String filename, boolean isResource)
throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
return jsonToMap(loadJson(filename, isResource).getAsJsonObject());
}
public static List<Object> loadJsonArray(String filename, boolean isResource)
throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
return jsonToList(loadJson(filename, isResource).getAsJsonArray());
}
private static JsonElement loadJson(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
return new JsonParser().parse(new InputStreamReader(FileLoader.openInputStream(filename, isResource), "UTF-8"));
}
public static Object parse(JsonElement json) {
if (json.isJsonObject()) {
return jsonToMap((JsonObject) json);
} else if (json.isJsonArray()) {
return jsonToList((JsonArray) json);
}
return null;
}
public static Map<String, Object> jsonToMap(JsonObject jsonObject) {
if (jsonObject.isJsonNull()) {
return new HashMap<String, Object>();
}
return toMap(jsonObject);
}
public static List<Object> jsonToList(JsonArray jsonArray) {
if (jsonArray.isJsonNull()) {
return new ArrayList<Object>();
}
return toList(jsonArray);
}
private static final Map<String, Object> toMap(JsonObject object) {
Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, JsonElement> pair : object.entrySet()) {
map.put(pair.getKey(), toValue(pair.getValue()));
}
return map;
}
private static final List<Object> toList(JsonArray array) {
List<Object> list = new ArrayList<Object>();
for (JsonElement element : array) {
list.add(toValue(element));
}
return list;
}
private static final Object toPrimitive(JsonPrimitive value) {
if (value.isBoolean()) {
return value.getAsBoolean();
} else if (value.isString()) {
return value.getAsString();
} else if (value.isNumber()){
return value.getAsNumber();
}
return null;
}
private static final Object toValue(JsonElement value) {
if (value.isJsonNull()) {
return null;
} else if (value.isJsonArray()) {
return toList((JsonArray) value);
} else if (value.isJsonObject()) {
return toMap((JsonObject) value);
} else if (value.isJsonPrimitive()) {
return toPrimitive((JsonPrimitive) value);
}
return null;
}
}
FileLoader.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileLoader {
public static Reader openReader(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
return openReader(filename, isResource, "UTF-8");
}
public static Reader openReader(String filename, boolean isResource, String charset) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
return new InputStreamReader(openInputStream(filename, isResource), charset);
}
public static InputStream openInputStream(String filename, boolean isResource) throws FileNotFoundException, MalformedURLException {
if (isResource) {
return FileLoader.class.getClassLoader().getResourceAsStream(filename);
}
return new FileInputStream(load(filename, isResource));
}
public static String read(String path, boolean isResource) throws IOException {
return read(path, isResource, "UTF-8");
}
public static String read(String path, boolean isResource, String charset) throws IOException {
return read(pathToUrl(path, isResource), charset);
}
#SuppressWarnings("resource")
protected static String read(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
protected static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
protected static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return FileLoader.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
}
If you want no-lib version, here is the solution with regex:
public static HashMap<String, String> jsonStringToMap(String inputJsonString) {
final String regex = "(?:\\\"|\\')(?<key>[\\w\\d]+)(?:\\\"|\\')(?:\\:\\s*)(?:\\\"|\\')?(?<value>[\\w\\s-]*)(?:\\\"|\\')?";
HashMap<String, String> map = new HashMap<>();
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(inputJsonString);
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
map.put(matcher.group("key"), matcher.group("value"));
}
}
return map;
}
Imagine u have a list of email like below. not constrained to any programming language,
emailsList = ["abc#gmail.com","def#gmail.com","ghi#gmail.com"]
Now following is JAVA code - for converting json to map
JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();
This is an old question and maybe still relate to someone.
Let's say you have string HashMap hash and JsonObject jsonObject.
1) Define key-list.
Example:
ArrayList<String> keyArrayList = new ArrayList<>();
keyArrayList.add("key0");
keyArrayList.add("key1");
2) Create foreach loop, add hash from jsonObject with:
for(String key : keyArrayList){
hash.put(key, jsonObject.getString(key));
}
That's my approach, hope it answer the question.
Using json-simple you can convert data JSON to Map and Map to JSON.
try
{
JSONObject obj11 = new JSONObject();
obj11.put(1, "Kishan");
obj11.put(2, "Radhesh");
obj11.put(3, "Sonal");
obj11.put(4, "Madhu");
Map map = new HashMap();
obj11.toJSONString();
map = obj11;
System.out.println(map.get(1));
JSONObject obj12 = new JSONObject();
obj12 = (JSONObject) map;
System.out.println(obj12.get(1));
}
catch(Exception e)
{
System.err.println("EROR : 01 :"+e);
}

Categories