can somebody show code which deserialize json to TreeMap? Some simple example which includes example of json
I'll show what I've tried
First of all I am newbie so forgive me
That's my json(probably i have mistakes even here):
{"Car":[{"mark":"AUDI_A3", "colour": "black"},
{"mark":"BMW_m3", "colour": "white"}]}
There is my code which does not work
public static void main(String[] args) {
open();
}
private static void open(){
try {
BufferedReader buff = new BufferedReader(new FileReader("C:\Users\\t1.json"));
String bf=null;
String json= null;
while((bf=buff.readLine())!=null){
json+=bf;
}
Gson gson = new Gson();
Type type = new TypeToken<TreeMap<String, SmallGuys>>(){}.getType();
TreeMap<String, SmallGuys> Platoon = gson.fromJson(json, type);
System.out.print(Platoon.keySet());
}
catch (Exception e){
System.out.println("There is a mistake");
}
}
With Jackson, I put some methods:
public static Object convertJsonRequestToObject(HttpServletRequest pRequest, Class<?> pObject) throws JsonParseException, JsonMappingException, IOException {
return new ObjectMapper().readValue(IOUtils.toString(pRequest.getInputStream(), StandardCharsets.UTF_8), pObject);
}
public static Map<String,Object> parseJsonToMap(String json) throws JsonParseException, JsonMappingException, IOException{
return new ObjectMapper().readValue(json, HashMap.class);
}
public static Map<String,Object> parseObjectToMap(Object object){
return (Map<String, Object>) new ObjectMapper().convertValue(object, Map.class);
}
//inverse
public static Object parseMapToObject(Map<?, ?> pMap, Class<?> pClass){
return new ObjectMapper().convertValue(pMap, pClass);
}
Related
I am facing issue in converting the nested list object to JSON.I am using object mapper and it is only converting the starting values and after that there is one arraylist inside it and it is not going through that list.
I have tried some basic iteration using JsonNode root = mapper.valueToTree(obj)so that i can iterate through the inner arraylist but i am not getting the result.I am new to this parsing conversion.
code snippet--
public class JsonUtils {
public static <T> String toJsonString(final T obj) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
String jsonString = null;
try {
//JsonNode root = mapper.valueToTree(obj);
jsonString = mapper.writeValueAsString(obj);
} catch (final JsonProcessingException e) {
throw e;
} catch (IOException e) {
throw e;
}
return jsonString;
}
public static <T> String toJsonString(final List<T> lstObject) throws JSONException, IOException {
final JSONArray jsonArray = new JSONArray();
for (final T object : lstObject) {
final String json = JsonUtils.toJsonString(object);
final JSONObject jsonObj = new JSONObject(json);
jsonArray.put(jsonObj);
}
return jsonArray.toString();
}
}
So here is the result which i am getting -
[2, [{"geoMarketId":1,"geoname":"AP","geoId":1,"checked":false},
{"geoMarketId":7,"geoname":"EP","geoId":2,"checked":false},
{"geoMarketId":16,"geoname":"Japan","geoId":3,"checked":true},
{"geoMarketId":18,"geoname":"LA","geoId":4,"checked":true},
{"geoMarketId":22,"geoname":"MEA","geoId":5,"checked":true},
{"geoMarketId":24,"geoname":"NA","geoId":6,"checked":false}]]
Actual Result which should come-
{"geoMarketId":1,"geoname":"AP","geoId":1,"checked":false,
marketName:{"marketname":JP,"marketname":"AP","marketname":MP}}
My json conversion is ignoring this inner list in the same index.
Is there any way my json class can iterate and also convert that innerlist to JSON?
The Jackson data binding documentation indicates that Jackson supports deserialising "Arrays of all supported types" but I can't figure out the exact syntax for this.
For a single object I would do this:
//json input
{
"id" : "junk",
"stuff" : "things"
}
//Java
MyClass instance = objectMapper.readValue(json, MyClass.class);
Now for an array I want to do this:
//json input
[{
"id" : "junk",
"stuff" : "things"
},
{
"id" : "spam",
"stuff" : "eggs"
}]
//Java
List<MyClass> entries = ?
Anyone know if there is a magic missing command? If not then what is the solution?
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
For Generic Implementation:
public static <T> List<T> parseJsonArray(String json,
Class<T> classOnWhichArrayIsDefined)
throws IOException, ClassNotFoundException {
ObjectMapper mapper = new ObjectMapper();
Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
T[] objects = mapper.readValue(json, arrayClass);
return Arrays.asList(objects);
}
try this
List<MyClass> list = mapper.readerForListOf(MyClass.class).readValue(json)
First create an instance of ObjectReader which is thread-safe.
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});
Then use it :
List<MyClass> result = objectReader.readValue(inputStream);
I was unable to use this answer because my linter won't allow unchecked casts.
Here is an alternative you can use. I feel it is actually a cleaner solution.
public <T> List<T> parseJsonArray(String json, Class<T> clazz) throws JsonProcessingException {
var tree = objectMapper.readTree(json);
var list = new ArrayList<T>();
for (JsonNode jsonNode : tree) {
list.add(objectMapper.treeToValue(jsonNode, clazz));
}
return list;
}
try {
ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
List<User> lstUser = null;
JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
lstUser = mapper.readValue(jp, tRef);
for (User user : lstUser) {
System.out.println(user.toString());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
here is an utility which is up to transform json2object or Object2json,
whatever your pojo (entity T)
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* #author TIAGO.MEDICI
*
*/
public class JsonUtils {
public static boolean isJSONValid(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringWriter sw = new StringWriter();
objMapper.writeValue(sw, object);
return sw.toString();
}
public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
if (indent == true) {
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
StringWriter stringWriter = new StringWriter();
objMapper.writeValue(stringWriter, object);
return stringWriter.toString();
}
public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper objMapper = new ObjectMapper();
obj = objMapper.readValue(content, clazz);
return obj;
}
#SuppressWarnings("rawtypes")
public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(content, new TypeReference<List>() {
});
return obj;
}
public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
return obj;
}
you could also create a class which extends ArrayList:
public static class MyList extends ArrayList<Myclass> {}
and then use it like:
List<MyClass> list = objectMapper.readValue(json, MyList.class);
I'm trying to use my weather API to get the weather condition for an area, I think I have everything functioning except for the data parsing part.
import java.net.*;
import java.io.*;
import com.google.gson.*;
public class URLReader {
public static URL link;
public static void main(String[] args) {
try{
open();
read();
}catch(IOException e){}
}
public static void open(){
try{
link = new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json");
}catch(MalformedURLException e){}
}
public static void read() throws IOException{
//little bit stuck here
}
}
Can anyone help me to finish this simple little project, I'm a beginner btw.
You can use javaQuery to do this more easily:
$.getJSON("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json", null, new Function() {
#Override
public void invoke($ j, Object... args) {
//if you are expecting a JSONObject, use:
JSONObject json = (JSONObject) args[0];
//otherwise, it would be: JSONArray json = (JSONArray) args[0];
//Then to more easily parse the JSON, do this:
Map<String, ?> map = $.map(json)
//if you are using an array instead, you can use: Object[] array = $.makeArray(json);
//Now just iterate through your map (or list) to get the data you want to parse.
}
});
Just open connection from URL and try to read JSON from it:
public static void read() throws IOException{
InputStream is = null;
try {
is = link.openConnection().getInputStream();
Reader reader = new InputStreamReader(is);
Map<String, String> jsonObj = gson.fromString(reader, new TypeToken<Map<String, String>>() {}.getType());
//TODO do next stuff
} finally{
if (is != null){
is.close();
}
}
}
If you want, you can bind jsonObj into whatever you want, please read documentation.
The Jackson data binding documentation indicates that Jackson supports deserialising "Arrays of all supported types" but I can't figure out the exact syntax for this.
For a single object I would do this:
//json input
{
"id" : "junk",
"stuff" : "things"
}
//Java
MyClass instance = objectMapper.readValue(json, MyClass.class);
Now for an array I want to do this:
//json input
[{
"id" : "junk",
"stuff" : "things"
},
{
"id" : "spam",
"stuff" : "eggs"
}]
//Java
List<MyClass> entries = ?
Anyone know if there is a magic missing command? If not then what is the solution?
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
For Generic Implementation:
public static <T> List<T> parseJsonArray(String json,
Class<T> classOnWhichArrayIsDefined)
throws IOException, ClassNotFoundException {
ObjectMapper mapper = new ObjectMapper();
Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
T[] objects = mapper.readValue(json, arrayClass);
return Arrays.asList(objects);
}
try this
List<MyClass> list = mapper.readerForListOf(MyClass.class).readValue(json)
First create an instance of ObjectReader which is thread-safe.
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});
Then use it :
List<MyClass> result = objectReader.readValue(inputStream);
I was unable to use this answer because my linter won't allow unchecked casts.
Here is an alternative you can use. I feel it is actually a cleaner solution.
public <T> List<T> parseJsonArray(String json, Class<T> clazz) throws JsonProcessingException {
var tree = objectMapper.readTree(json);
var list = new ArrayList<T>();
for (JsonNode jsonNode : tree) {
list.add(objectMapper.treeToValue(jsonNode, clazz));
}
return list;
}
try {
ObjectMapper mapper = new ObjectMapper();
JsonFactory f = new JsonFactory();
List<User> lstUser = null;
JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
lstUser = mapper.readValue(jp, tRef);
for (User user : lstUser) {
System.out.println(user.toString());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
here is an utility which is up to transform json2object or Object2json,
whatever your pojo (entity T)
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* #author TIAGO.MEDICI
*
*/
public class JsonUtils {
public static boolean isJSONValid(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringWriter sw = new StringWriter();
objMapper.writeValue(sw, object);
return sw.toString();
}
public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
if (indent == true) {
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
StringWriter stringWriter = new StringWriter();
objMapper.writeValue(stringWriter, object);
return stringWriter.toString();
}
public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper objMapper = new ObjectMapper();
obj = objMapper.readValue(content, clazz);
return obj;
}
#SuppressWarnings("rawtypes")
public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(content, new TypeReference<List>() {
});
return obj;
}
public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
return obj;
}
you could also create a class which extends ArrayList:
public static class MyList extends ArrayList<Myclass> {}
and then use it like:
List<MyClass> list = objectMapper.readValue(json, MyList.class);
I'm trying to get the hits of a google search from a string of the query.
public class Utils {
public static int googleHits(String query) throws IOException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String json = stringOfUrl(googleAjax + query);
JsonObject hits = new Gson().fromJson(json, JsonObject.class);
return hits.get("estimatedResultCount").getAsInt();
}
public static String stringOfUrl(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
IOUtils.copy(url.openStream(), output);
return output.toString();
}
public static void main(String[] args) throws URISyntaxException, IOException {
System.out.println(googleHits("odp"));
}
}
The following exception is thrown:
Exception in thread "main" java.lang.NullPointerException
at odp.compling.Utils.googleHits(Utils.java:48)
at odp.compling.Utils.main(Utils.java:59)
What am I doing incorrectly? Should I be defining an entire object for the Json return? That seems excessive, given that all I want to do is get one value.
For reference: the returned JSON structure.
Looking the returned JSON, it seems that you're asking for the estimatedResultsCount member of the wrong object. You're asking for hits.estimatedResultsCount, but you need hits.responseData.cursor.estimatedResultsCount. I'm not super familiar with Gson, but I think you should do something like:
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
I tried this and it worked, using JSON and not GSON.
public static int googleHits(String query) throws IOException,
JSONException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
URL searchURL = new URL(googleAjax + query);
URLConnection yc = searchURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String jin = in.readLine();
System.out.println(jin);
JSONObject jso = new JSONObject(jin);
JSONObject responseData = (JSONObject) jso.get("responseData");
JSONObject cursor = (JSONObject) responseData.get("cursor");
int count = cursor.getInt("estimatedResultCount");
return count;
}