dsl-json
dsl-json copied to clipboard
Question about create a Java POJO with an anonymous object
I have this json
[
2308,
{
"a": [
"1958.38000",
2,
"2.05000000"
],
"b": [
"1957.81000",
3,
"3.95000000"
],
"c": [
"1957.32000",
"0.55407557"
],
"v": [
"1422.39220916",
"1524.19647295"
],
"p": [
"1959.08106",
"1960.58108"
],
"t": [
1671,
1949
],
"l": [
"1914.37000",
"1914.37000"
],
"h": [
"1991.81000",
"2004.15000"
],
"o": [
"1975.90000",
"1997.23000"
]
},
"type",
"XCT"
]
The problem is that the values are anonymous. How can I deserialize this String with the dsljson Framework? I don't know how to describe an anonymous values. And to deserialize without a POJO is not working either.
What is the correct way to deserialize this JSON?
import java.util.Map;
public class TestDSL {
public static void main(String[] args) throws IOException {
byte[] jsonObject = "[2308,{\"a\":[\"1958.38000\",2,\"2.05000000\"],\"b\":[\"1957.81000\",3,\"3.95000000\"],\"c\":[\"1957.32000\",\"0.55407557\"],\"v\":[\"1422.39220916\",\"1524.19647295\"],\"p\":[\"1959.08106\",\"1960.58108\"],\"t\":[1671,1949],\"l\":[\"1914.37000\",\"1914.37000\"],\"h\":[\"1991.81000\",\"2004.15000\"],\"o\":[\"1975.90000\",\"1997.23000\"]},\"ticker\",\"ETH/USDT\"]".getBytes();
DslJson<Object> dslJson = new DslJson<>();
dslJson.deserialize(Map.class,jsonObject,jsonObject.length );
}
Hi,
I would assume deserialize Object.class or deserializeList of Object should give you what you want. This is a JSON Array, so you can't convert it into a map, only into a collection
Hi
Thank you for your answer What do you mean with "I would assume deserialize Object.class or deserializeList of Object should give you what you want." Can you please show a short Java example`?
If you don't know the schema upfront, you can ask for unknown object type via Object.class There is relevant example here: https://github.com/ngs-doo/dsl-json/blob/b7d8795a405dc7faeb2a1b4699497ab628cfcd08/tests-java8/src/test/java/com/dslplatform/json/OnUnknownTest.java#L109
But basically both
Object res = dslUnknown.deserialize(Object.class, input, input.length);
List<Object> col = dslUnknown.deserializeList(Object.class, input, input.length);
Should give you what you want as long as you setup dslUnknown to support such deserialization (which is not a recommended thing)
Thank you, very kind of you.
Ok this one works:
new DslJson.Settings<>()
.resolveReader(Settings.UNKNOWN_READER)
.resolveWriter(Settings.UNKNOWN_WRITER)
.includeServiceLoader());
ArrayList um1 = (ArrayList) dslUnknown.deserialize(Object.class, jsonObject, jsonObject.length);
Now I have to use this example dsl-json/tests-java8/src/test/java/com/dslplatform/json/OnUnknownTest.java to create a POJO? Or is it not possibible to create a POJO for this JSON?
It certainly is. There are various examples on how to do it.