You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
Answer from Manos Nikolaidis on Stack OverflowYou are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
For any one who looks for answer yet:
1.Add jackson-databind library to your build tools like Gradle or Maven
2.in your Code:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
Converting a JSON string into an object with a list of objects inside it - Java - Stack Overflow
How to convert list data into json in java - Stack Overflow
java - Convert json to Object List - Stack Overflow
java - How to convert JSON file to List - Stack Overflow
Videos
You have to create another class say Output as
import java.util.List;
public class Output {
public List<Token> getTokens() {
return tokens;
}
public void setTokens(List<Token> tokens) {
this.tokens = tokens;
}
private List<Token> tokens;
}
and then use
Output output = new Gson().fromJson(json, Output.class);
then you can use output to get list of tokens and go further for suggestion etc
You can use Jackson's TypeReference to achieve this, e.g.:
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<List<Token>> typeReference = new TypeReference<List<Token>>() {};
List<Token> tokens = objectMapper.readValue("<json_stribg>", typeReference);
You can read more about TypeReference here.
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
You can use the below methods to read from a file and convert the JSON array to a List of Questions.
public String readJsonFromFile(String filePath) throws IOException, ParseException {
String json = Files.readString(Paths.get("file path"));
return new JSONParser().parse(json).toString();
}
public List<Question> convert(String JsonString) throws JsonMappingException, JsonProcessingException {
ObjectMapper om = new ObjectMapper();
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(List.class, Question.class);
List<Question> questions = om.readValue(JsonString, typeReference);
return questions;
}
If your JSON keys and Java class fields are different, use @JsonPropery annotation to map keys to fields
import com.fasterxml.jackson.annotation.JsonProperty;
public class Question {
@JsonProperty("question")
private String title;
@JsonProperty("answer 1")
private String a1;
@JsonProperty("answer 2")
private String a2;
@JsonProperty("answer 3")
private String a3;
@JsonProperty("correct answer")
private String cA;
//setters & getters
}
Required Jars:
jackson-annotations.jar
jackson-core.jar
jackson-databind.jar
json-simple.jar //used to parse Json file to String
You have two steps
Get JSON string from the file, use read file from assets
Extract items from the JSON string use How do I convert a JSON array into a Java List. I'm using svenson
With Jackson you would do something like:
String jsonStr = "...";
ObjectReader reader = new ObjectMapper().reader();
List<Map<String, Object>> objs = reader.readValue(jsonStr);
Map<String, Object> myFirstObj = objs.get(0);
myFirstObj.get("data");
myFirstObj.get("what");
// and so on
Or even better you can create a pojo and do:
String jsonStr = "...";
ObjectMapper mapper = new ObjectMapper();
List<MyPojo> myObjs = mapper.readValue(jsonStr, new TypeReference<List<MyPojo>>() {});
MyPojo myPojo = myObjs.get(0);
myPojo.getData();
myPojo.getWhat();
// and so on
There are several libraries out there that will parse JSON, such as GSon and Jackson. If the functionality isn't provided out-of-box, you can write a custom deserializer that will do what you need.
Use Jackson or GSON to read the JSON as List or array of expected type.
With Jackson:
ObjectMapper mapper = new ObjectMapper(); // reuse if multiple calls
MyPOJO[] pojos = mapper.readValue(jsonSource, MyPojo[].class); // with `List`, need to use `TypeReference`
// or, if you do not have matching MyPOJO type:
List<Object> pojosAsMaps = mapper.readValue(jsonSource, List.class);
There are many other ways you could do it, like reading as JSON tree (JsonNode).
It all depends on whether you can easily model structure as Java class (if so, most convenient) or not.
Just use the org.json.* package.
You can look it up under http://www.json.org/javadoc/org/json/package-summary.html JSONArray and JSONObject will be the most interesting code snippets.
Also your JSON-Object is not really well formated, you should make an Array of your Objects first, like:
users : [{
"shortname" : "g",
"moreAttributes" : ""
}, {
"shortname" : "h",
"moreAttributes" : ""
}]
Using this array-structure you can add objects information outside the array. For example an errormessage.
now you can access your json-file with some simple methods:
JSONObject jObj = //the json file you loaded
JSONArray jArr = jObj.getArray("users");
JSONObject jUser;
//at this point you can iterate over your array and get information via:
jUser = jArr.getJSONObject(1)
//now you can get all the information from the jUser object
//e.g.
jUser.getString("shortname");
I want to convert the following text file into a java object list, HashMaps seem not complext enough as the text file is Json
info = [{"key":"1",
"request":"ok",
"group": "user"},{...},...{}]