Parsing POJO to JSON Object - java

I have to convert a POJO to JSON object but i am encountering a problem.
My POJO has four variables and their getters and setters.
private String RouteCoord;
private String RouteName;
private String freqArray;
private Double AvgTime;
I have declared a list of objects
List<KPIsStructure> listOfKPIsObjects = new ArrayList<>();
I run a for loop in which i create instances of my POJO class and add them to the already declared list (listOfKPIsObjects)
for (int i=0;i<routes.length;i++){
KPIsStructure innerObject = new KPIsStructure();
innerObject.setRouteCoord(routes[i][1]);
innerObject.setRouteName(routes[i][0]);
innerObject.setAvgTime(AvgTime[i]);
innerObject.setfreqArray(freqArray[i]);
listOfKPIsObjects.add(innerObject);
}
Then there is this another for loop to make a nested JSON Object
for (int i=0;i<listOfKPIsObjects.size();i++){
JSONObject temp = new JSONObject(listOfKPIsObjects.get(i));
processedJson.put("journey_"+(i+1), temp);
}
I return processedJson. The problem is the result is missing one of the variables (String freqArray) of the POJO class.
{"journey_1":{"avgTime":12.283334,"routeCoord":"435,345-789,1011","routeName":"tty-keskustori"},"journey_2":{"avgTime":12.283334,"routeCoord":"123,456-789,1011","routeName":"hervanta-tty"},"journey_3":{"avgTime":12.283334,"routeCoord":"123,456-789,1011","routeName":"kaleva-keskustori"}}
I have tried passing the variables of the class as string and it works and it also shows that the string freqArray is not empty.
String toJson = "{\"RouteName:"+listOfKPIsObjects.get(i).getRouteName()+",RouteCoordinates:"+listOfKPIsObjects.get(i).getRouteCoord()+",AvgTime:"+listOfKPIsObjects.get(i).getAvgTime()+",VisitFrequency:"+listOfKPIsObjects.get(i).getfreqArray()+"}";
Doing it this way takes away the idea of mapping from POJO to JSON object and vice versa and makes it inconvenient.
Any ideas what i might be doing wrong here. I am using org.json.

Related

How do you deserialize a JSON Array with multiple types using GSON?

I have a JSON String as follows
{
"sort": [1000.0, "id123456789"]
}
I'm trying to deserialize this JSON String into an Object using GSON.fromJson(str, SortArray.class) but I don't know what to do since the JSON Array contains a double and a String, which are two different types.
Does anyone know how I could model this array in a class so I can deserialize it?
I have tried the following but it does not work
#Gson.TypeAdapters(nullAsDefault = true)
#Value.Immutable
public interface SortArray {
#Value.Parameter
double sortScore();
#Value.Parameter
String id();
}

How can I deserialize a list of enums using Jackson JSON?

I'm working on a configuration system. I'd like to be able to load config values from a JSON file and have them "automagically" convert to the Java type I need. I'm using Jackson for the JSON parsing. For primitive types like floats and strings, it's no big deal, but I'm running into a snag with enums.
Let's say I have the following enum:
public enum SystemMode
{
#JsonProperty("Mode1")
MODE1("Mode1"),
#JsonProperty("Mode2")
MODE2("Mode2"),
#JsonProperty("Mode3")
MODE3("Mode3");
private final String name;
private SystemMode(String name)
{
this.name = name;
}
#Override
#JsonValue
public String toString()
{
return this.name;
}
}
Now, let's say I want to represent a list of values of this enum for a given config variable using the following JSON representation:
{
"Project" : "TEST",
"System" : {
"ValidModes" : ["Mode1", "Mode2"]
}
}
And I'd like to be able to do something like the following:
ArrayList<SystemMode> validModes = (ArrayList<SystemMode>) configurator.getConfigValue("/System/ValidModes");
For reference, my configurator class's getConfigValue method is essentially a thin wrapper over the Jackson JSON parsing:
public Object getConfigValue(String JSON_String)
{
JsonNode node = JsonNodeFactory.instance.objectNode().at(JSON_String);
return objectMapper.convertValue(node, Object.class);
}
(The real method has some exception checking that has been omitted for clarity).
Now, when I call the above, Jackson correctly deduces that I want an ArrayList and fills it. However, instead of getting an ArrayList of SystemMode enums, I get an ArrayList of Strings and immediately throw an exception when I attempt to use the list. I have tried several different ways of representing the data to no avail. It seems no matter what I try, Jackson wants to return a list of strings instead of a list of enums.
So my question is this:
How can I make Jackson (version 2.9.4) JSON properly deserialize a list of enum values in a way that is compatible with my single "Object getConfigValue()" method?
The following will provide the correct binding for your enum.
public List<SystemMode> getConfigValue(String path)
{
JsonNode node = JsonNodeFactory.instance.objectNode().at(path);
return objectMapper.convertValue(node, new TypeReference<List<SystemMode>>(){});
}
The second option is to convert the list of String yourself, for example:
List<SystemMode> result = jsonResult.stream().map(SystemMode::valueOf).collect(Collectors.toList());
Third option:
public <T>List<T> getConfigValue(String path, Class<T> type)
{
JsonNode node = JsonNodeFactory.instance.objectNode().at(path);
CollectionType toType =
objectMapper.getTypeFactory().constructCollectionType(List.class, type);
return objectMapper.convertValue(node, toType);
}

Mapping JSON to Java objects with different keywords

My company has a webserver API that provides search results in JSON format. I'm responsible for developing an Android app that consumes that API, and I have made some classes that model the objects in the JSON responses.
For the sake of habit and my own preference, I use to write my code in English only. However, most of the JSON keys are not in English. This way, I cannot readily use GSON to convert the JSON strings into Java Objects -- at least that is what I think.
I was wondering if there is any way to reference just once per class the connection between the JSON key and their corresponding instance variables in the code. In a way that after referenced, I could simply instantiate objects from JSON and create JSON strings from objects.
Is that possible?
Example:
// Java code
class Model {
String name;
Integer age;
}
// JSON with keys in Portuguese
{
"nome" : "Mark M.", # Key "nome" matches variable "name"
"idade" : 30 # Key "idade" matches variable "age"
}
Use the #SerializedName annotation.
Here is an example of how this annotation is meant to be used:
public class SomeClassWithFields {
#SerializedName("name") private final String someField;
private final String someOtherField;
public SomeClassWithFields(String a, String b) {
this.someField = a;
this.someOtherField = b;
}
}
The following shows the output that is generated when serializing an instance of the above example class:
SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
Gson gson = new Gson();
String jsonRepresentation = gson.toJson(objectToSerialize);
System.out.println(jsonRepresentation);
===== OUTPUT =====
{"name":"a","someOtherField":"b"}
Source: SerializedName Javadocs

Serializing list of objects with flexjson

I am playing with flexjson and Google Cloud Endpoints. My model which I need to serialize is:
public class SampleModel {
Long id;
DateTime createdAt;
String message;
OtherModel other;
}
I just created DateTimeObjectFactory to find a way of creating DateTime objects (lacks of no arg constructor). Now I have question about OtherModel and SampleModel as well.
I want to serialize in fact a List of SampleModel. So here is my code:
List<SampleModel> sampleList = new ArrayList<SampleModel>();
// ...
// adding some items to sampleList
// ...
String s = new JSONSerializer().deepSerialize(sampleList);
I want to deepSerialize it for now to avoid some unserializated fields, but just for now.
When I want to deserialize s I do that:
sampleList = new JSONDeserializer<List<SampleModel>>()
.use("other", OtherModel.class)
.use(DateTime.class, new DateTimeObjectFactory())
.deserialize(s);
I think that everything is just ok in that kind of deserializing, because I can see in logs deserialized object. But in fact when I want to get item from that new sampleList I get an error:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.test.games.testapi.model.SampleModel
If I have good understanding every not trivial object will be deserialized as Map if I don't point the right class to deserializer. So this error means that script didn't know SampleModel? What is the meaning of this?

Parsing JSON array with gson

I am having trouble parsing my JSON which i get from javascript.
The format of JSON is this:
[{"positions":[{"x":50,"y":50},{"x":82,"y":50},{"x":114,"y":50},{"x":146,"y":50}]},{"positions":[{"x":210,"y":50},{"x":242,"y":50},{"x":274,"y":50}]}]
So far i have been able to get this far:
{"positions":[{"x":50,"y":50},{"x":82,"y":50},{"x":114,"y":50},{"x":146,"y":50}]}
But i also need to now create a class with those positions. I havnt been working on the class, since i tried printing out the output first, but i am unable to break it down further. I am getting this error message:
java.lang.IllegalStateException: This is not a JSON Array.
And my code is this:
JsonParser parser = new JsonParser();
String ships = request.getParameter("JSONships");
JsonArray array = parser.parse(ships).getAsJsonArray();
System.out.println(array.get(0).toString());
JsonArray array2 = parser.parse(array.get(0).toString()).getAsJsonArray();
System.out.println(array2.get(0).toString());
I have also tried to do it this way:
Gson gson = new Gson() ;
String lol = (gson.fromJson(array.get(0), String.class));
System.out.println(lol);
In which case i get:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT
In the end, i want to loop through positions, creating class for each "positions", which contains a List with another class Position, which has the int x, y.
Thank you for your time.
Define your classes and you will get everything you need using gson:
public class Class1 {
private int x;
private List<Class2> elements;
}
And the inner class:
public class Class2 {
private String str1;
private Integer int2;
}
Now you can parse a json string of the outer class just like that:
gson.fromJson(jsonString, Class1.class);
Your error while using Gson is that you try to parse a complex object in String, which is not possible.

Categories