deserializing json with arrays - json

im using jackson to deserialize some Json. I am reading through a large json document and pulling out blocks and telling jackson to take that block and deserialize it to an object that I created (Actually several objects as there are nested arrays) in java to match the json.
The code im using to deserialize is
fooObject newFoo = mapper.readValue(newNode,fooObject.class);
The problem is there is a value in the block that is sometimes a hash such as
addWidgetStrategy={"get":2,"spend":6,"textLabel":"bikes"}
and sometimes an array
addWidgetStrategy=[{"get":1.5,"spend":3,"textLabel":"thursday"},{"get":3,"spend":5,"textLabel":"tuesday"}]
So in fooObject I need to deal with addWidgetStrategy which has its own object. If in fooObject I put
public addWidgetStrategy addWidgetStrategy;
The above works until it tried to deserialize an array
If I put
public List<addWidgetStrategy> addWidgetStrategy;
it works just for arrays and blows up when its just a single hash
How can I parse that same Json element addWidgetStrategy regardless if its an array or a single hash?

For arrays it should be:
fooObject[] newFoo = mapper.readValue(newNode,fooObject[].class);
You can read it like this:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
fooObject[] newFoo = mapper.readValue(jsonNode,fooObject[].class);
...
} else {
fooObject newFoo = mapper.readValue(jsonNode,fooObject.class);
....
}

Related

How to convert Object to Jooq JSON

I have a String (jsonData) being mapped to json via Jackson Object mapper as below to JaxB.
var completeJson = objectMapper.readValue(jsonData, Data.class);
myDto.setFirstName(completeJson.getFirstName())
myDto.setLastName(completeJson.getLastName()))
.....
.....etc..etc
I'm able to map to the above strings just fine. However, I'm having problems mapping
to a jooq JSON object. I guess I will now have to convert jsonData to jooq JSON.
How would I do this?
JSON newJson = objectMapper.(best method to use);
myDto.setJsonSource(newJson)
Or maybe I have to create some sort of wrapper?
DTO configured by jooq
public myDto setJsonSource(JSON jsonSource) {
this.jsonSource = jsonSource;
return this;
}
The org.jooq.JSON type is just a wrapper around a string, so why not just use:
JSON json = JSON.json(objectMapper.writeValueAsString(object));

How to remove escaping slashes from a json inside another json?

I have the following json, that is being populated by:
new Gson().toJson(batch.getProducts());
But when im adding it to my main JSONObject, the fact that it's a value of a json is doing all the json (even the keys) be escaped.
{"name":"Ufud","store":2,"products":"[{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Teste2\",\"stock\":2,\"value\":19.9}]"}
Is there any method to prevent this?
If you're going to manipulate your json in future you may consider converting it not into a string, but into a JsonElement which can be quite easily added to already existing JsonObject
JsonObject mainObject = getMainObject(); //method which creates your main object. You can change it to variable reference
JsonElement productsElement = new Gson().toJsonTree(batch.getProducts()); //converting your object into JsonElement
mainObject.add("products", productsElement); //insering products element into object.
String json = new Gson().toJson(mainObject); //converting object with products element into a json string

Grails JSON Converter

I have a method in my main controller that return a string that I want to render as JSON.
So I am importing "import grails.converters.JSON" and calling
myMethod() as JSON
, and it works fine. But when I need to get some details of the json response in my integration test.
So in my integration test I have:
void testfoo() {
def bar = controller.myMethod();
def bar.name; //fails
JSON.parse(bar.toString()).name; // doesn't fail
....
..
}
any idea why I need to convert it to a string and then again to a JSON, since it already a JSON?
The value you get back from your method is a grails.converters.JSON, which is not a directly accessible JSON tree as such, but simply an object that knows how to serialize itself as JSON when required. If you want direct access to the JSON tree structure then you need to tell the grails.converters.JSON object to serialize itself and then pass that JSON to JSON.parse to turn it into a JSONElement (or one of its subclasses, in this case presumably a JSONObject).

Mapping unpredictable keys from JSON to POJO

I am using the Jackson JSON library to map JSON streams into POJO's.
My JSON's keys have unpredictable names.
i.e
{
"Random_ID":
{
"Another_Random_ID":
{
"some_key": "value"
"some_key1": "value1"
}
}
...
}
I would like to map this request to a POJO (with the same structure), however the mapper will fail since there is no such setXXX (where XXX is a random_id - since i cannot predict the name).
What would be the best way to map this request to the corresponding object without manually parsing it with createJsonParser.
If names are unpredictable, POJOs are not the way to go.
But you can use the Tree Model, like:
JsonNode root = objectMapper.readTree(jsonSource);
and access it as a logical tree. Also, if you do want to convert the tree (or any of sub-trees, as identified by node that is the root of sub-tree), you can do:
MyPOJO pojo = objectMapper.treeToValue(node, MyPOJO.class);
and back to tree
JsonNode node = objectMapper.valueToTree(pojo);

difference between json string and parsed json string

what is the difference between json string and parsed json string?
for eg in javascript suppose i have a string in the json format say [{},{}]
parsing this string will also produce the same thing.
So why do we need to parse?
It's just serialization/deserialization.
In Javscript code you normally work with the object, as that lets you easily get its properties, etc, while a JSON string doesn't do you much good.
var jsonobj = { "arr": [ 5, 2 ], "str": "foo" };
console.log(jsonobj.arr[1] + jsonobj.str);
// 2foo
var jsonstr = JSON.stringify(jsonobj);
// cannot do much with this
To send it to the server via an Ajax call, though, you need to serialize (stringify) it first. Likewise, you need to deserialize (parse) from a string into an object when receiving JSON back from the server.
Great question. The difference is transfer format.
JSON is only the 'Notation' of a JavaScript Object, it is not actually the JavaScript 'object-literal' itself. So as the data is received in JSON, it is just a string to be interpreted, evaluated, parsed, in order to become an actual JavaScript 'Object-Literal.
There is one physical difference between the two, and that is quotation marks. It makes sense, that JSON needs to be a string to be transferred. Here is how:
//A JavaScript Object-Literal
var anObj = { member: 'value'}
//A JSON representation of that object
var aJSON = { "member":"value" }
Hope that helps. All the best! Nash
I think a parsed json string should be the string data into the actual javascript objects and data arrays (or whichever language the json string contains)
The JSON object contains methods for parsing JSON and converting values to JSON.
It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
JSONParser parser = new JSONParser();
Object object = parser.parse(Message.toString());
JSONObject arObj = (JSONObject) object;