I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.
[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.
[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]
You need to have a model calss. lets say your json-string is like this :
String temp_json_string = "{ \"history\":\"L\", \"loan\":\"12345\", \"status\":\"1\"}";
Go to this or similar site and generate a class for your temp_json_string by pasting json string in that link and get class, choose getters and setters if you need.
http://www.jsonschema2pojo.org/
Create a new gson/jackson object (import that library either maven or build jre system path), convert the string to this "BankLoanDetails" class.
Gson gson = new Gson();
BankLoanDetails my_loan_pojo = gson.fromJson(temp_json_string,
BankLoanDetails.class);
your my_loan_pojo is pojo representing your json string.
Did you check at Safely turning a JSON string into an object
I am extending Akash's answer.
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
---
ObjectMapper mapper = new ObjectMapper();
List<DTO> list = mapper.readValue(JSONString, TypeFactory.collectionType(List.class, DTO.class));
First Create a POJO Class something like this:
public class Loan {
private String history;
private String loan;
private int status;
\\ generate getters,setters and toString method
}
Now parse your json and convert into jSONArray (import json-simple library),
String path = "path to your json file";
File f = new File(path);
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(f));
JSONArray jsonArray = (JSONArray) obj;
Now
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(jsonArray);
List<Loan> loanList = Arrays.asList(mapper.readValue(jsonStr, Loan[].class));
for (Loan l : loanList)
System.out.println(l);
Note : your json array contains different keys as history(first object) and History(second object). change it to history as in Loan class, data member is history.