I'm working on a project at the moment that requires me to take in a various currency pairs and generate a response object from an API call response. I'm using jackson to map the JSON response to java objects then reading data from an ArrayList generated. The problem is the JSON response can have the different currency pairing strings as a key for the list of pairing data. Here's what a typical response looks like:
{"error":[],"result":{"XXBTZUSD":[[1647062100,"39091.2","39184.9","39088.9","39139.0","39150.9","59.22447291",161],}[1647063000,"39138.9","39188.4","39138.9","39151.2","39174.2","2.92905848",126]]}
The problem arises when I try to pull data from a different currency pair as my result object is hard coded to pull the data for the JSON key XXBTZUSD. Here's what my result object looks like:
public class Result{
#JsonProperty("XXBTZUSD")
public ArrayList<ArrayList<Object>> candles;
public int last;
}
I was thinking having the #JsonProperty be variable and pass in the key from the json response to correct pull the currnecy pair I set it to, but JsonProperty needs to be a constant. The only way around this I can see is to have a ton of different classes for each currency pair but that would be inefficient and take around 15 separate classes to do. I'm not too familiar with the jackson library. If anyone has any ideas of how to solve this I would be greatly appreciative, I've been trying to figure out a way around this for awhile now. Thank you!
If keys can be different, one option is to use a Map. Your Result class won't be needed, parse the result property into Map<String, Object>. Then extract like this:
Map<String, Object> result = deserialize();
ArrayList<ArrayList<Object>> arrays = (ArrayList<ArrayList<Object>>) result.get("XXBTZUSD");
Just change property depending on which currency pair you need.
Another option is writing custom deserializer, in which to always put value in your candles field, regardless of how the property is named in json.
Related
This is a kind of specific question and I couldn't get any information on this topic in the javadoc of Gson.
Currently, I'm trying to parse an Json(1){ "foo":"bar", "bar":"foo" } to an Object Entity. Normally I would map these values to the Entity Object with the fields foo and bar, however I'd like to be more independent from the API.
For (1) I'd have
public class Entity {
String foo;
String bar;
}
But if we test another Endpoint the resulting Json (2) would look like
{ "notFoo":"bar", "notBar":"foo" }
which makes my previous constructed Entity useless, and I'd need to create a new Class with the respective fields for that.
So my actual question is:
Is there a generic (more generic than my example) approach to
push the Json into a GenericEntity -> g.fromJson(response.getBody(),GenericEntity.class); that every field of the json will be successfully mapped, even when using different Endpoints?
Alternatively, are there other dependencies which support that out of the box?
You do not have a deserialisation problem, you have a problem of not knowing how to represent possibly heterogeneous data.
There is no point of saying it should be Object as it should definitely be some type downstream of Object, possibly more than one. Solve this problem first: define all types that you may want to use for all use cases and then you will most likely see how to solve the deserialisation problem.
Surely, for any JSON text defined between {...} you can always go for Map<String, Object> where Object is one of:
further Map<String, Object> where Object follows these rules
List<Object> where Object follows these rules
String
one of atomic types or their boxed values
With the above rules you can represent more or less everything and you can write Gson deserialisers to deliver you those types based on the JSON type of each node (while iterating via the JSON tree). However, it is not really clear what use could you make of such a heterogenous untyped data structure.
You can use the annotation #serializedName as written in Multiple GSON #SerializedName per field?. But the schema must be the same, you only have alternatives to key name.
I'm parsing json with Gson but I'm struggling with the data I'm getting. This is part of an API out of my control (openFDA) so changing that might not be an option.
Here's the json I'm strugling with: https://api.fda.gov/device/event.json?search=device.generic_name:generator&limit=10
There are some fields that are not consistent, for example remedial_action. Sometimes it comes out like this:
"remedial_action": [
"Recall"
]
and in other results like this:
"remedial_action": ""
So it's either an array or a plain string. Is there a way to handle this? If not possible in Gson, any other json parsing library that can help?
I created my pojos here in case someone needs the code. There are a few files created from that and didn't want to spam them here. I can add them if needed.
Update: The bug has been confirmed and it's scheduled for a fix.
It is possible through GSON, by using a TypeAdapter.
Here are the initial steps I would use to do that:
Create a POJO that contains the array and the String. Let's call it RemedialAction.
In your original POJO, create an attribute of the new class.
Create a class that extends TypeAdapter<RemedialAction>.
Override the read() and write() methods and create the logic in them.
That should be a little hard to parse, though. Read this tutorial for more information.
Note: you can customize getRemedialAction() to give you only the valid return -- array or String.
I am trying to insert a document(json string) in a mongo db. One of the key "profile" of this has a value which is a json string. So, basically its a nested json structure. I know its possible to insert a nested json by abusing collection-refs / one-may relationships in the document class.
The issue I am facing here is that the json structure of the nested part is not fixed and hence cannot be abstracted to a java class as it is a custom data json fetched from social networking APIs. Defining "profile" as Java string inserts profile data with slashes thus escaping the double-quotes, curly brackets, etc. in json data .
Is there any other way without casting it to another object.
The way to go is probably to make profile a Map<String, Object> in the containing class. This way, you can store arbitrary data within it.
class MyDocument {
Map<String, Object> profile;
}
The answer of using a Map was a little unclear to me... how do you convert an arbitrary JSON String to a Map in a way that Spring Data will persist it as-is?
I found that using a property of type "com.mongodb.DBObject" works. Then set your property using JSON.parse:
profile = (DBObject) JSON.parse(arbitraryJSONString)
I am deserialising a json object as below
{
"b":"value1",
"a":"value2",
"d":"value3",
"c":"value4",
"f":"value5",
"e":"value6"
}
But i am getting ClassCastException as below
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.LinkedHashMap
My deserialisation code is
LinkedHashMap<String, String> map = new JSONDeserializer<LinkedHashMap<String, String>>().deserialize(JSONstring);
But when i use HashMap instead of LinkedHashMap it works but output gets sorted as below (Its not original order).
{
a=value2,
b=value1,
c=value4,
d=value3,
e=value6,
f=value5
}
I want to get the output in original order.
I found this related link
Flex JSON unable to properly serialize/deserialize LinkedHashMap
but didn't get how to use ObjectFactory.
I would appreciate any help!
Thanks in advance!
(Disclaimer: I just downloaded flexjson and debugged through its source code, so my answer might be slightly incomplete.)
In short:
You generally cannot get the entries in original order using flexjson.
Even writing a custom ObjectFactory will not work.
This is most likely intended and correct.
In detail:
First, the use of generics in new JSONDeserializer<LinkedHashMap<String,String>>() only affects the compilable code, flexjson cannot use this information to actually return a LinkedHashMap<String,String> (this is because the compiler removes the generic and the implementing class has no information of this generic type at runtime).
So, looking deeper into what happens during deserialization, it seems that during parsing the input string, the data is automatically converted to the correct type (string, date, number, list, etc.). This is done using some kind of autodetection of the required data type, because JSON does not provide type information in its data, so flexjson has a build-in list to support data types. It can also use custom mappings to assign values to object properties when proper class information is given (on serialization, flexjson adds a field class to the data to store this type information; or you can manually set this, see documentation).
But the main point is that - according to http://json.org -
An object is an unordered set of name/value pairs.
flexjson internally uses an (unordered) map to store the temporary object keys and values. Even if you tell flexjson to return the data as a LinkedHashMap the data is yet put into a HashMap before it will be converted to a LinkedHashMap, so the original order is not available at that point. (This might be fixed by replacing the map creation in flexjson.JSONTokener, line 442 with a LinkedHashMap but I didn't try that myself.)
Conclusion:
It looks like this behaviour even cannot be changed by providing a custom ObjectFactory, so as far as I understand the code, you cannot retain the original field order. (May I ask why this is important for your project?)
So, if anybody finds a solution anyway, don't hesitate to correct me.
I am using GSON to decode JSON strings that are returned from our server. I haven't had any problems, until I ran into this one particular JSON return from the API. The return is in the following format:
"success":1,"errors":[],"data":{"524":{"id":"524"}, "525":{"id":"525"}}
For the other returns I had data as an array of a class of my own creation, but for this return it says that it is an object and not an array. So how should I format my class?
***edit: What I am having trouble with is that the '524' and '525' fields are not static names. They are dependent on what the user's credentials are. There could be fields 323, 324, 325 or a single one 123. It all depends. How would I be able to handle this dynamically?
SOLVED*
What I had to was make 'data' a <String, Object> hashmap in my custom class. Then after the first decoding, I turned 'data' into an array of type Object []. Then for each Object[i], I converted it into a JSON string. After that I used gson.fromJson() to convert it into what I had originally intended for it to be.
If the API is giving inconsistent results and you can't find a reason on your end why it is doing so, one option is to parse the object into a GSON JSONObject o = gson.fromJson(String) and then convert the data to a list if it is not one already by doing o.getElement("data").isList(), etc..
When this is complete, you can then create the object via gson.fromJson(JSONObject,Class). The alternative is to have two classes, one for each instance, but this seems sloppy if this is the only reason to have two different classes.
GSON is correct. From server reply data is object with two members that are objects also. To be array data should have square brackets [] instead of curly brackets {}. More about JSON format here.
Server format was changed or you tried another API version or someone made bug on server side.