How to decode JSON file created with GSON in Java? - java

I've successfully created a JSON file with gson but now that I want to parse that same file, the encoding gets all messed up.
This is the code I use to read the JSON file:
BufferedReader jsonFile = new BufferedReader(new FileReader("file.json"));
Map<String, List<long[]>> trafficInput = new HashMap<>();
trafficInput = gson.fromJson(jsonFile, HashMap.class);
I can't seem to figure out how to ensure the file gets parsed the right way.
For instance, this valid JSON code from the file:
{"paris":[[1485907200000,182184411,41274],[1485993600000,151646118,36697],"london":[[1485907200000,30200160,155827]}
...gets parsed like this:
{"paris":[[1.4859072E12,1.82184411E8,41274.0],[1.4859936E12,1.51646118E8,36697.0],"london":[[1.4859072E12,3.020016E7,155827.0]}
This messes up the rest of the code as the longs aren't longs anymore.
For instance, if I try to print out a value, like so:
System.out.println(trafficInput.get("paris").get(0)[0]);
... I get this error:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [J
Any help?

This is happening because of the following line:
trafficInput = gson.fromJson(jsonFile, HashMap.class);
This line instructs gson to deserialize the string into HashMap without specifying any type, and hence, gson applies its default conversion mechanism (i.e. converting Number into double etc). This is why Sysout statement results in a ClassCastException because that element is not an array.
All you need to do is to specify a TypeToken while calling fromJson method and it will take care of types. e.g.:
Gson gson = new Gson();
Type type = new TypeToken<Map<String, List<long[]>>>(){}.getType();
Map<String, List<long[]>> trafficInput = new HashMap<>();
trafficInput = gson.fromJson("{\"paris\":[[1485907200000,182184411,41274],[1485993600000,151646118,36697]],\"london\":[[1485907200000,30200160,155827]]}", type);
System.out.println(trafficInput);
System.out.println(gson.toJson(trafficInput));
The above snippet prints numbers without scientific notation.

Related

Android: gson.toJson converter giving empty string for Android objects

I'm trying to covert Java object to json using Gson library, but its not working as expected and returning empty string,
my code:
String ie = new String("Jack");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
it returns:
{}
Please let me know if anything wrong with library, I tried with other Objects as well all returning null value like for Intent Object, ApplicationInfo etc
If you want convert string to json object, your string must be json as well.
For example:
String ie = new String("{\"name\": \"Jack\"}");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);

Trying to read a JSON file into a Map using Jackson

I have a JSON file with this structure...
{"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"}
{"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}
which doesn't have a key or commas separating each object. So when I use this code...
File input = new File("test.json");
ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(input, Map.class);
the obj variable only has the first line in the json file which makes sense as it doesn't know what the key is.
I tried adding one by wrapping the objects like so...
{ "Key": [
{"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"},
{"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}
] }
including adding the commas to separate each as the file did not have any commas to separate them.
While this works...
I have multiple json files that I have to work with
The file sizes are a bit big so it takes a long time to add they "Key" wrap like I did in the example.
I'm hoping to avoid this altogether but not sure if I can. Is there a way to read the json file using the original format into a Map so I can then filter the data as needed?
There is a simple solution that doesn't require file modification. Read your file line by line and then feed a single line to your ObjectMapper. You will get Many instances of Maps that you can store in a List, JsonArray or another map that you will need to create in your code. your code make look like:
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object> list = new ArrayList<>()
try (
BufferedReader br = new BufferedReader(new FileReader(new File("test.json")))) {
String line;
while((line = br.readLine()) != null) {
Map obj = mapper.readValue(line, Map.class);
list.add(obj)
}

convert arrayList multimap to json string?

I have the following code:
public static void postHttpStream(ArrayListMultimap<String, String> fcmbuildProperties){
HttpClient client = new HttpClient();
Gson gson = new Gson();
System.out.println(fcmbuildProperties);
String jsonString = gson.toJson(fcmbuildProperties);
System.out.println(jsonString);
}
where fcmbuildProperties is an ArrayListMultimap. I try to convert that to JSON here: String jsonString = gson.toJson(fcmbuildProperties); But this returns an empty array. What do I need to do instead?
This is the input that fcmbuildProperties contain : {build.name=[test_project], build.timestamp=[1425600727488], build.number=[121]}
I need to convert this to Json. with key/values.
Use ArrayListMultimap#asMap()
String jsonString = gson.toJson(fcmbuildProperties.asMap());
Gson considers ArrayListMultimap as a Map and ignores its internal state which actually manages the multimap. asMap returns a corresponding Map instance which you can serialize as expected.

Getting java object back from JSON

I am putting some java objects in the Json at server side
like this :
ArrayList<VisjsNode>visjsNodes = new ArrayList<VisjsNode>();
ArrayList<VisjsConnection> visjsConnections = new ArrayList<VisjsConnection>();
String jsondata = null;
org.json.JSONObject object = new org.json.JSONObject();
try {
object.put("nodes", visjsNodes);
object.put("connections", visjsConnections);
jsondata = object.toString();
Now is there a way I can get these objects back from this json (jsondata) at client side
I am doing this:
com.google.gwt.json.client.JSONValue jsonValue = JSONParser.parseStrict(jsondata);
com.google.gwt.json.client.JSONObject jsonObject = jsonValue.isObject();
jsonValue = jsonObject.get("nodes");
Now I am trying this to get ArrayList back , by doing this
ArrayList<VisjsNode>visjsNodesFromjson = jsonValue ;
But its not compiling ,it says Incompatable types...
Can you please guide how we can retrieve the Java Object back from Json ..
That's because you're using two different JsonObject class. First you use the one which comes from org.json (org.json.JsonObject) and the other is com.google.gwt.json.client.JSONObject. Nevertheless, they're named similar, they're completely different classes.

Gson gson = new Gson().toJson(data) - incompatible types

I've been following a tutorial on turning an array of objects into JSON but I've come across a few errors that I can't find a solution for.
CODE
Line 60 - 64
Gson gson = new Gson().toJson(data);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(gson);
ERRORS
Line 60
incompatible types
found : java.lang.String
required: com.google.gson.Gson
Gson gson = new Gson().toJson(data);
Line 64
cannot find symbol
symbol : method write(com.google.gson.Gson)
location: class java.io.PrintWriter
response.getWriter().write(gson);
Does anyone know how to properly do what I'm trying?
It certainly looks from your error messages that it should be
String gson = new Gson().toJson(data);
which seems to address both of those errors.
Use
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
Exmaple:
Employee obj = new Employee(); // Your java object
...
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
response.getWriter().write(json);

Categories