I'm trying to deserialize a nested array from a JSON response. It's the first time I've ever gotten an array of arrays and I'm not quite sure how to structure my class to handle it.
{
"prices": [
[
1641670404234,
0.01582586939240936
],
[
1641674037525,
0.015999047707867396
],
[
1641677655158,
0.016072905257982606
]
...
],
}
If the brackets were { instead of [
{
"prices": {
{
1641670404234,
0.01582586939240936
},
{
1641674037525,
0.015999047707867396
},
{
1641677655158,
0.016072905257982606
}
}
...
}
I could use
#SerializedName("prices")
private List<Price> prices;
public class Price {
private long date;
private BigDecimal price;
}
However since it is [ instead, I am quite unsure how to structure it.
I've tried adding another List wrapper to it but that throws an error
#SerializedName("prices")
private List<List<Price>> prices;
IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 26 path $.prices[0][0]
I've also tried wrapping it with a JSONArray
#SerializedName("prices")
private List<JSONArray<Price>> prices;
but that's not quite right
I've tried searching other SO answers but I could not find any examples where it's two consecutive [ [ brackets.
They are all { [ or [ {.
What's the correct way to do it?
The proper way to solve this is to write a custom TypeAdapter for your Price class. This has the advantage that you can keep your model classes as is (with a List<Price> prices field), and have them represent more closely the actual data. If instead you parsed the JSON data as List<List<BigDecimal>> or similar, then you would have to manually validate that the JSON data is wellformed and have to convert the List<BigDecimal> to a Price object yourself.
Here is how a TypeAdapter implementation for your Price class could look like:
class PriceTypeAdapter extends TypeAdapter<Price> {
#Override
public void write(JsonWriter out, Price value) throws IOException {
out.beginArray();
out.value(value.date);
out.value(value.price);
out.endArray();
}
#Override
public Price read(JsonReader in) throws IOException {
in.beginArray();
Price priceObj = new Price();
priceObj.date = in.nextLong();
// nextString() automatically converts JSON numbers to String, if necessary
// This is similar to how Gson's default adapter for BigDecimal works
priceObj.price = new BigDecimal(in.nextString());
in.endArray();
return priceObj;
}
}
Note: Alternatively to reading the BigDecimal manually as shown here, you could create this type adapter inside a TypeAdapterFactory and get the default Gson adapter for BigDecimal. This allows reusing Gson's built-in adapters inside your own type adapter, but here for BigDecimal that overhead is probably not worth it.
You can then either register your adapter on a GsonBuilder instance or you can place an #JsonAdapter annotation on your Price class, which references the adapter. In case you use the GsonBuilder approach, you might want to create a null-safe variant of your adapter by calling nullSafe() on it (or you implement null handling in the adapter manually).
Assuming this is the correct JSON:
{
"prices": [
[
1641670404234,
0.01582586939240936
],
[
1641674037525,
0.015999047707867396
],
[
1641677655158,
0.016072905257982606
]
]
}
Then you can use this model to deserialize data to:
JAVA:
public class PricesModel {
public ArrayList<ArrayList<Double>> prices;
}
KOTLIN:
data class PricesModel (
#SerializedName("prices" ) var prices : ArrayList<ArrayList<Double>> = arrayListOf()
)
Handy JSON converters to Java and Kotlin.
Related
I have some JSON that can hold an array of both arrays of maps, or just maps (I know this seems dumb). I'm having trouble identifying what the ArrayOrMap class should look like to allow deserialisation of this structure.
{
"example": [
[
{
"key1": "value1"
},
{
"key2": "value2"
}
],
{
"key3": "value3"
}
]
}
I'm trying to deserialise this using ObjectMapper, and Jackson's #JsonCreator annotations:
#Getter
static class StackOverflowExample {
private final ArrayOrMap[] example;
#JsonCreator
StackOverflowExample (
#JsonProperty("example") ArrayOrMap[] example,
) {
this.example = example;
}
}
#Getter
static class ArrayOrMap {
???
}
...
// code that attempts to deserialise
final StackOverflowExample result = objectMapper.readValue(
data,
StackOverflowExample.class
);
I'm trying to deserialise the JSON into an array of objects, each of which can be either an array of maps, or just a map, but I don't know what the class for ArrayOrMap should look like. It seems like object deserialisation always requires a key of some kind, but here I'm just deserialising an array of objects, so I don't have a key to look at.
I'm aware that the structure of this JSON is pretty poor to begin with, but changing it now would take significant effort.
Any help is appreciated, thanks!
I need help with parsing, I've tried to create a different kind of model classes, but no use, please help me out here. the json looks like this:
[
[
1518909300000,
"0.08815700",
"0.08828700",
"0.08780000",
"0.08792900",
"1727.93100000",
1518910199999,
"152.11480375",
5118,
"897.71600000",
"79.04635703",
"0"
],
[
1518910200000,
"0.08788400",
"0.08824200",
"0.08766200",
"0.08810000",
"1789.81300000",
1518911099999,
"157.20177729",
6201,
"898.89500000",
"78.95697080",
"0"
]
]
and I'm trying to parse it using data class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class KlineResponse {
public List<Kline> getKlineList() {
return klineList;
}
public List<Kline> klineList;
public class Kline {
#JsonProperty("4")
Double close;
#JsonProperty("8")
Integer tradesNumber;
public Double getClose() {
return close;
}
public void setClose(Double close) {
this.close = close;
}
public Integer getTradesNumber() {
return tradesNumber;
}
public void setTradesNumber(Integer tradesNumber) {
this.tradesNumber = tradesNumber;
}
}
}
and this line
mapper.readValue(response.getBody(), new TypeReference<List<KlineResponse>>(){})
or
mapper.readValue(response.getBody(), KlineResponse.class)
but each time the error:
Can not deserialize instance of pt.settings.model.KlineResponse out of START_ARRAY token,
please help
The core issue is that you receive an array of arrays where you expect and array of objects. Changing mapper.readValue(response.getBody(), KlineResponse.class) to mapper.readValue(response.getBody(), Object[].class) confirms it.
You have a couple of options on how to proceed:
Change from Jackson to standard JSON parsing, as suggested by #cricket_007 on his answer
Instead of mapping it to an object try to access the JSON differently. See #jschnasse's answer for an example.
Change the format of text you parse, if you can
If you can't change the format of the input then you can either
Create a constructor and annotate it with #JsonCreator, like instructed here
Parse the input as Object array and feed the parsed array into a constructor of your own
You don't need any java classes. There are no JSON objects to deserialize, only arrays.
In the second case, Jackson is expecting { "klineList": [] }
In the first, [{ "klineList": [] }, { "klineList": [] }]
And a Kline object is only parsable as {"4": 0.0, "8": 0 } (replace zeros with any value of same type)... So really unclear why you expected that to work given that data... The annotations are not the index of the lists.
Plus, your lists have both strings and integers, so you can only deserialize as TypeReference<List<List<Object>>>, then iterate that to parse ints, floats, or strings
I might recommend you use a standard json parser, not an objectmapper
Use JsonNode together with JPointer. Avoid to create a POJO and work directly on the data via JsonNode.
ObjectMapper mapper = new ObjectMapper();
JsonNode matrix = mapper.readValue(in, JsonNode.class);
matrix.forEach(array -> {
System.out.println("Next Values:");
System.out.println(array.at("/4").asDouble());
System.out.println(array.at("/8").asInt());
});
Prints
Next Values:
0.087929
5118.0
Next Values:
0.0881
6201.0
I am struggling to find a way to serialize / deserialize this JSON output to a Java class? Can anyone provide code sample?
[
{
"topic": "this is my topic"
},
[
{
"name": "John"
},
{
"age": 100
}
]
]
My current attempt uses this Javabean:
public class Test {
private String topic;
private List<Person> listOfPersons;
}
Which I try to deserialize data into using Gson:
gson.fromJson(this.json, Test[].class);
But the deserialization fails, because Gson is looking for a list of persons in the JSON, but it doesn't exist.
It doesn't seem like having an object next to an array, inside an array, is sensical. It would make sense to put things this way:
{
"topic": "this is my topic",
"listOfPersons" : [
{
"name": "John",
"age": 100
},
{
... another person
}
]
}
Then you could just have a Person class:
public class Person {
private String name;
private int age;
}
...and you could deserialize with the code you already have.
The problem here is that your JSON data is syntactically correct, but semantically ambiguous. And by that I mean, it appears to represent a polymorphic array, where each item in the array is of a different type.
In addition, the portion representing a 'person' seems to have been de-normalized horribly, where each attribute of a person is represented as a separate object in an array. Quite weird indeed. Unfortunately its really impossible to tell what types are represented just by looking at the data alone, and there are no hints provided to allow Gson to deserialize the data for you. The best you can do in this case is manually parse the information.
Test test = new Test();
JsonArray rootArray = new JsonParser().parse(jsonString);
test.setTopic(rootArray.get(0).get("topic");
Person person = new Person();
JsonArray personArray = rootArray.get(1);
person.setName(personArray.get(0).get("name"));
person.setAge(personArray.get(1).get("age"));
test.setListOfPersons(Arrays.asList(person));
I'm trying to parse some JSON containing a nested array. I'd like the array to map to a list of child objects within the parent I'm mapping. Here is the (slightly abbreviated) JSON and Java classes
JSON:
{
"id": "12121212121",
"title": "Test Object",
"media$content": [
{
"plfile$audioChannels": 1,
"plfile$audioSampleRate": 18000,
},
{
"plfile$audioChannels": 2,
"plfile$audioSampleRate": 48000,
},
{
"plfile$audioChannels": 2,
"plfile$audioSampleRate": 48000,
}
]
}
Java classes
class MediaObject {
#JsonProperty("id")
private String id;
#JsonProperty("title")
private String title;
#JsonProperty("media$Content")
private List<MediaContent> mediaContent;
... getters/setters ...
}
class MediaContent {
#JsonProperty("plfile$audioChannels")
private int audioChannels;
#JsonProperty("plfile$audioSampleRate")
private int audioSampleRate;
... getters/setters ...
}
I'd like to be able to deserialize using annotations along with the standard mapper code, i.e.
mapper.readValue(jsonString, MediaObject.class)
Everything works fine with the "id" and "title" fields, but my list of MediaContent objects always comes up null. This seems like something Jackson should be able to handle without much trouble, can anyone see what I'm doing wrong here?
The name of the json field is wrong - the attribute is not media$Content, rather media$[c]ontent. Otherwise I do not see why it will not work.
I am hitting a RESTful 3rd party API that always sends JSON in the following format:
{
"response": {
...
}
}
Where ... is the response object that needs to be mapped back to a Java POJO. For instance, sometimes the JSON will contain data that should be mapped back to a Fruit POJO:
{
"response": {
"type": "orange",
"shape": "round"
}
}
...and sometimes the JSON will contain data that should be mapped back to an Employee POJO:
{
"response": {
"name": "John Smith",
"employee_ID": "12345",
"isSupervisor": "true",
"jobTitle": "Chief Burninator"
}
}
So depending on the RESTful API call, we need these two JSON results mapped back to one of the two:
public class Fruit {
private String type;
private String shape;
// Getters & setters for all properties
}
public class Employee {
private String name;
private Integer employeeId;
private Boolean isSupervisor;
private String jobTitle;
// Getters & setters for all properties
}
Unfortunately, I cannot change the fact that this 3rd party REST service always sends back a { "response": { ... } } JSON result. But I still need a way to configure a mapper to dynamically map such a response back to either a Fruit or an Employee.
First, I tried Jackson with limited success, but it wasn't as configurable as I wanted it to be. So now I am trying to use XStream with its JettisonMappedXmlDriver for mapping JSON back to POJOs. Here's the prototype code I have:
public static void main(String[] args) {
XStream xs = new XStream(new JettisonMappedXmlDriver());
xs.alias("response", Fruit.class);
xs.alias("response", Employee.class);
// When XStream sees "employee_ID" in the JSON, replace it with
// "employeeID" to match the field on the POJO.
xs.aliasField("employeeID", Employee.class, "employee_ID");
// Hits 3rd party RESTful API and returns the "*fruit version*" of the JSON.
String json = externalService.getFruit();
Fruit fruit = (Fruit)xs.fromXML(json);
}
Unfortunately when I run this I get an exception, because I have xs.alias("response", ...) mapping response to 2 different Java objects:
Caused by: com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field me.myorg.myapp.domain.Employee.type
---- Debugging information ----
field : type
class : me.myorg.myapp.domain.Employee
required-type : me.myorg.myapp.domain.Employee
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /response/type
line number : -1
version : null
-------------------------------
So I ask: what can I do to circumvent the fact that the API will always send back the same "wrapper" response JSON object? The only thing I can think of is first doing a String-replace like so:
String json = externalService.getFruit();
json = json.replaceAll("response", "fruit");
...
But this seems like an ugly hack. Does XStream (or another mapping framework) provide anything that would help me out in this particular case? Thansk in advance.
There are two ways with Jackson:
test manually that the wanted keys are there (JsonNode has the necessary methods);
use JSON Schema; there is one API in Java: json-schema-validator (yes, that is mine), which uses Jackson.
Write a schema matching your first object type:
{
"type": "object",
"properties": {
"type": {
"type": "string",
"required": true
},
"shape": {
"type": "string",
"required": true
}
},
"additionalProperties": false
}
Load this as a schema, validate your input against it: if it validates, you know you need to deserialize against your fruit class. Otherwise, make the schema for the second item type, validate against it as a security measure, and deserialize using the other class.
There are code examples for the API, too (version 1.4.x)
If you do know the actual type, it should be relatively straight-forward with Jackson.
You need to use a generic wrapper type like:
public class Wrapper<T> {
public T response;
}
and then the only trick is to construct type object to let Jackson know what T there is.
If it is statically available, you just do:
Wrapper<Fruit> wrapped = mapper.readValue(input, new TypeReference<Wrapper<Fruit>>() { });
Fruit fruit = wrapped.response;
but if it is more dynamically generated, something like:
Class<?> rawType = ... ; // determined using whatever logic is needed
JavaType actualType = mapper.getTypeFactory().constructGenericType(Wrapper.class, rawType);
Wrapper<?> wrapper = mapper.readValue(input, actualType);
Object value = wrapper.response;
but either way it "should just work". Note that in latter case you may be able to use base types ("? extends MyBaseType"), but in general dynamic type can't be specified.