Can you build the array as an object before writing it, rather than bothering with all the individual pieces?
CopyObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.createArrayNode();
int i = 0;
while (i < 6) {
array.add(mapper.createArrayNode().add("" + i++).add("" + i++));
}
System.out.println(array);
Results in:
Copy[["0","1"],["2","3"],["4","5"]]
If you're not dealing with several megabytes of data or very tight memory constraints, this might turn out to be more maintainable as well.
Answer from Chris on Stack OverflowCan you build the array as an object before writing it, rather than bothering with all the individual pieces?
CopyObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.createArrayNode();
int i = 0;
while (i < 6) {
array.add(mapper.createArrayNode().add("" + i++).add("" + i++));
}
System.out.println(array);
Results in:
Copy[["0","1"],["2","3"],["4","5"]]
If you're not dealing with several megabytes of data or very tight memory constraints, this might turn out to be more maintainable as well.
Copy JsonGenerator jg = new JsonFactory().createJsonGenerator(System.out);
jg.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
jg.writeStartArray();
int i = 0;
while (i < 6)
{
jg.writeStartArray();
jg.writeObject(i++);
jg.writeObject(i++);
jg.writeEndArray();
}
jg.writeEndArray();
jg.flush();
OUTPUT:
Copy [["0","1"],["2","3"],["4","5"]]
Do you need a json like this...?
java - How to parse a JSON string to an array using Jackson - Stack Overflow
How to parse Json array with 2 or more different types using Jackson?
http://www.baeldung.com/jackson-inheritance
You'll need to have those types inherit from one base class though.
Also; that is really bad JSON.
More on reddit.comjava - Jackson how to transform JsonNode to ArrayNode without casting? - Stack Overflow
(JAVA) JsonPath.read() / Jackson JSONArray messing up JSON format
Videos
I finally got it:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
The other answer is correct, but for completeness, here are other ways:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
Hi guys, I've been searching online and stackoverflow but can't seem to find an answer to this. Basically the API i'm calling returns a json array as the root object. The two objects inside this array are different types. I have defined two Java classes to represent these two types and I'm wanting to read the json and convert them into my java object with jackson. Seems like there isn't a way to do this??
simple example of my objects:
class Type1 {
String name
}
class Type2 {
long age
}The json coming from the api looks like this:
[
{
"name" : "mickey"
},
{
"age" : 100
}
]How can I tell jackson to read in this "tree" but convert it to some object that is holding these two?
EDIT Here is a reply I made to another comment:
Ok, it seems like nobody is understanding what I'm saying. For one, I don't have control of the api I'm calling. I get what I get and have to deal with it.
What that api returns is a json ARRAY as the ROOT object. There are two objects in that array. Those two objects are NOT the same types.
IF that array was holding objects of the same type, i could do this:
MyObjects[] myobjs = new Objectmapper().readValue("some json array here", MyObjects[].class);But like I said, i can't do this. Because the array is not holding objects of the same type. It would be more akin to a tuple like in python.
http://www.baeldung.com/jackson-inheritance
You'll need to have those types inherit from one base class though.
Also; that is really bad JSON.
Use a custom deserializer. See f.e. this link.
In your case the custom deserializer will look at the JsonNode and the properties it contains and instantiate the proper type.
Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode has most of the functions that you would typically associate with array nodes from other APIs. As such, you do not need to cast to an ArrayNode to use. Here's an example:
JSON:
{
"objects" : ["One", "Two", "Three"]
}
Code:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
Output:
"One"
"Two"
"Three"
Note the use of isArray to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your data structure, but it's available should you need it (and this is no different from most other JSON libraries).
In Java 8 you can do it like this:
import java.util.*;
import java.util.stream.*;
List<JsonNode> datasets = StreamSupport
.stream(obj.get("datasets").spliterator(), false)
.collect(Collectors.toList())
Just started using this and not finding any answers online, but I'm web-scraping and the method I am using is messing up the format so I can't deserialize to an object when I use the JSON path "$..itemsV2[*]" . It takes the quotes away from the key-value pairs and changes ':' to '=', which is giving me the following error:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token '\_\_typename': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
When I use "$..itemsV2" then it leaves the original format alone and serializes just fine, but it only returns the first item in the JSON Array. Any ideas?
link: https://pastebin.com/uQ4Dkpmh
The link should work now
SOLVED: turns out ObjectMapper has a super handy method
WmProduct[] wmProducts = objectMapper.convertValue(jsonItemArray,WmProduct[].class);
The problem is not in your code but in your json:
{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}
this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:
class EmployeList{
private List<Employe> compemployes;
(with getter an setter)
}
and to deserialize the json simply do:
EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);
If your json should directly represent a list of employees it should look like:
[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]
Last remark:
List<Employee> list2 = mapper.readValue(jsonString,
TypeFactory.collectionType(List.class, Employee.class));
TypeFactory.collectionType is deprecated you should now use something like:
List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,
Employee.class));
/*
It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"[email protected]","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"[email protected]"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"[email protected]"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"[email protected]"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
//use the add method from the list and returns it.
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}