I m trying to parse a JSON file and store it in an list. I m getting this error :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
Here is my JSON file
{ "budgetList":[
{
"label":"Salary Tim",
"category":"Monthly Income",
"real":1590,
"estimated":1590,
"date":"",
"month":"",
"year":"",
"type":"Income"
},
{
"label":"Salary Tom",
"category":"Monthly Income",
"real":1540,
"estimated":1540,
"date":"",
"month":"",
"year":"",
"type":"Income"
}
]
}
Here is my code
Budget :
public class Budget {
private String label;
private String category;
private int real;
private int estimated;
private Date date;
private int year;
private String type;
....
....
}
My service :
List<Budget> budgets = objectMapper.readValue(new File("src/main/resources/json/new_exercise.json"), TypeFactory.defaultInstance().constructCollectionType(List.class,
Budget.class));
Where am I wrong?
Thanks in advance.
ANSWER FOUND
Code is
ObjectMapper objectMapper = new ObjectMapper();
List<Budget> budgets = null;
JsonNode node = objectMapper.readTree(new File("src/main/resources/json/new_exercise.json"));
node = node.get("budgetList");
TypeReference<List<Budget>> typeRef = new TypeReference<List<Budget>>(){};
budgets = objectMapper.readValue(node.traverse(), typeRef);
can you, use GSON library? Is very simple
Reader reader = new InputStreamReader(new
FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new
TypeToken>() {}.getType());
I think that the only problem is when Date and integer parser when is empty. but you can register adapters like:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch (ParseException e) {
return null;
}
}
});
Reader reader = new InputStreamReader(new
FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new
TypeToken>() {}.getType());
It works for you?, and dont forget to validate you json. "
Related
I get following exception.
Caused by: java.lang.ClassCastException: Cannot cast java.util.LinkedList to com.example.weltliste.Task
at this line: tasks.add(g.fromJson(in, Task.class));
Here is the full method + my custom deserializer
public class FileHandler {
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
Gson g = new GsonBuilder().setPrettyPrinting()
.registerTypeAdapter(Task.class, new TaskSerializer())
.registerTypeAdapter(Task.class, new TaskDeserializer()).create();
public List<Task> read(InputStream stream) throws IOException {
InputStreamReader in = new InputStreamReader(stream);
List<Task> tasks = null;
tasks.add(g.fromJson(in, Task.class));
return tasks;
}
Here is my custom deserializer
public class TaskDeserializer implements JsonDeserializer<List<Task>> {
#Override
public List<Task> deserialize(JsonElement json,
Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<Task> tasks = new LinkedList<>();
JsonArray jsonArray = json.getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject;
jsonObject = jsonArray.get(i).getAsJsonObject();
String title = jsonObject.get("title").getAsString();
String value = jsonObject.get("value").getAsString();
LocalDateTime date = LocalDateTime.parse(jsonObject.get("date").getAsString());
boolean checked = jsonObject.get("checked").getAsBoolean();
tasks.add(new Task(title, value, date, checked));
}
return tasks;
}
}
I have a method that writes my objects in to a JSON file, is there a way I can read the objects and store them back in to an ArrayList? Ideally I would like to store the objects in to the 'music' ArrayList.
Write to JSON method:
public class TimelineLayout extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel timelineLabel;
static ArrayList<Music> music = new ArrayList<>();
public static void saveMusic(ArrayList<Music> music, String filename) {
String fn;
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(music, new TypeToken<ArrayList<Music>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String json = gson.toJson(jsonArray);
try {
//write converted json data to a file named "objects.json"
if (filename != null) {
fn = "objects.json";
} else {
fn = filename + ".json";
}
FileWriter writer = new FileWriter(fn);
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON Objects:
[{
"artist": "Usher",
"title": "U got it bad",
"genre": "Pop",
"duration": 3.01,
"year": 2003
},
{
"artist": "Coldplay",
"title": "Viva la vida",
"genre": "Rock n ",
"duration": 2.56,
"year": 2001
}
]
Trying to parse using GSON library:
public static List<Music> loadMusic() {
ArrayList<Music> musicList = new ArrayList<>();
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
try {
BufferedReader br = new BufferedReader(new FileReader("objects.json"));
JsonElement jsonElement = jsonParser.parse(br);
//Create generic type
java.lang.reflect.Type type = new TypeToken<List<Music>>() {
}.getType();
return gson.fromJson(jsonElement, type);
} catch (IOException e) {
e.printStackTrace();
}
return musicList;
}
I'm using this method to parse a JSON string, but it is too slow... is there a better way to do it?
Thanks
synchronized private void parseCategories(String response){
try{
JSONArray categoriesJSONArray = new JSONArray (response);
// looping through All Contacts
for(int i = 0; i < categoriesJSONArray.length(); i++){
JSONObject currentCategory = categoriesJSONArray.getJSONObject(i);
String label="";
String categoryId="";
// Storing each json item in variable
if(currentCategory.has("label"))
label = currentCategory.getString("label");
if(currentCategory.has("id"))
categoryId = currentCategory.getString("id");
if(
label!=null &&
categoryId!=null
)
{
Category toAdd = new Category(categoryId, label);
categories.add(toAdd);
}
}
//Alphabetic order
Collections.sort(
categories,
new Comparator<Feed>() {
public int compare(Feed lhs, Feed rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
}
);
Intent intent = new Intent("CategoriesLoaded");
LocalBroadcastManager.getInstance(mAppContext).sendBroadcast(intent);
}catch (JSONException e) {
e.printStackTrace();
}
}
Here's try following code to start with. You would need Gson library for it.
Gson gson=new Gson();
MyBean myBean=gson.fromJson(response);
Note: Here MyBean class contains the fields present in you json string for e.g. id, along with getter and setters. Rest of all is handled by Gson.
Here's a quick demo.
import com.google.gson.annotations.SerializedName;
public class Box {
#SerializedName("id")
private String categoryId;
// getter and setter
}
Say you JSON looks as following:
{"id":"A12"}
You can parse it as follows:
class Parse{
public void parseJson(String response){
Gson gson=new Gson();
Box box=gson.fromJson(response,Box.class);
System.out.println(box.getCategoryId());
}
}
Output :
A12
For more on Gson visit here
Use GSON library. You can convert your object to json string like the following example:
MyClass MyObject;
Gson gson = new Gson();
String strJson = gson.toJson(MyObject);
I am trying to convert json from a text file into a java object.
I have tried both the jackson library, I put in the dependency and what not. My json file has both camel case and underscores, and that is causing an error when running my program. Here is the code that I used for when relating to the gson librar and it does not do anything, the output is the same with or without the code that I placed.
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
try
{
BufferedReader br = new BufferedReader(new FileReader("/test.json"));
// convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e)
{
e.printStackTrace();
}
Now I also tried the jackson library. Here is the code i used
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
InputStream is = Test_Project.class.getResourceAsStream("/test.json");
SampleDto testObj = mapper.readValue(is, SampleDto.class);
System.out.println(testObj.getCreatedByUrl());
I am not sure what to do,
This simple example works like a charm:
DTOs
public class SampleDTO
{
private String name;
private InnerDTO inner;
// getters/setters
}
public class InnerDTO
{
private int number;
private String str;
// getters/setters
}
Gson
BufferedReader br = new BufferedReader(new FileReader("/tmp/test.json"));
SampleDTO sample = new Gson().fromJson(br, SampleDTO.class);
Jackson
InputStream inJson = SampleDTO.class.getResourceAsStream("/test.json");
SampleDTO sample = new ObjectMapper().readValue(inJson, SampleDTO.class);
JSON (test.json)
{
"name" : "Mike",
"inner": {
"number" : 5,
"str" : "Simple!"
}
}
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
/**
* Read object from file
*/
Person person = mapper.readValue(new File("/home/document/person.json"), Person.class);
System.out.println(person);
}
A common way of getting both array of json in file or simply json would be
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);
List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);
The file.json needs to be placed in the resources folder. If your file only has a json block without json array square brackets [] , you can skip the CollectionType
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);
Also refer here for original question from where I have drawn.
I'm not able to return a JSONArray, instead my object appears to be a String. the value of myArray is the same value as jsonString. The object is a String object and not a JSONArray. and both jsonString and myArray prnt:
[{"id":"100002930603211",
"name":"Aardvark Jingleheimer",
"picture":"shortenedExample.jpg" },
{"id":"537815695",
"name":"Aarn Mc",
"picture":"shortendExample.jpg" },
{"id":"658471072",
"name":"Adrna opescu",
"picture":"shortenedExample.jpg"
}]
How can I convert this to an actual Java JSONArray? thanks!
//arrPersons is an ArrayList
Gson gson = new Gson();
String jsonString = gson.toJson(arrPersons);
JsonParser parser = new JsonParser();
JsonElement myElement = parser.parse(jsonString);
JsonArray myArray = myElement.getAsJsonArray();
I think you can do what you want without writing out a json string and then re-reading it:
List<Person> arrPersons = new ArrayList<Person>();
// populate your list
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(arrPersons, new TypeToken<List<Person>>() {}.getType());
if (! element.isJsonArray()) {
// fail appropriately
throw new SomeException();
}
JsonArray jsonArray = element.getAsJsonArray();
public JSONArray getMessage(String response){
ArrayList<Person> arrPersons = new ArrayList<Person>();
try {
// obtain the response
JSONObject jsonResponse = new JSONObject(response);
// get the array
JSONArray persons=jsonResponse.optJSONArray("data");
// iterate over the array and retrieve single person instances
for(int i=0;i<persons.length();i++){
// get person object
JSONObject person=persons.getJSONObject(i);
// get picture url
String picture=person.optString("picture");
// get id
String id=person.optString("id");
// get name
String name=person.optString("name");
// construct the object and add it to the arraylist
Person p=new Person();
p.picture=picture;
p.id=id;
p.name=name;
arrPersons.add(p);
}
//sort Arraylist
Collections.sort(arrPersons, new PersonSortByName());
Gson gson = new Gson();
//gson.toJson(arrPersons);
String jsonString = gson.toJson(arrPersons);
sortedjsonArray = new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return sortedjsonArray;
}
public class PersonSortByName implements Comparator<Person>{
public int compare(Person o1, Person o2) {
return o1.name.compareTo(o2.name);
}
}
public class Person{
public String picture;
public String id;
public String name;
}