Converting JSON response to Java object - java

I need to convert a JSON response into Java Object, but I am gettin nullpointerException.
Here is my model class:
public class Cheque {
private String payeeName;
private String accountNumber;
private String ifsCode;
private String micr;
private String bankName;
public Cheque() {
super();
// TODO Auto-generated constructor stub
}
public Cheque(String payeeName, String accountNumber, String ifsCode, String micr, String bankName) {
super();
this.payeeName = payeeName;
this.accountNumber = accountNumber;
this.ifsCode = ifsCode;
this.micr = micr;
this.bankName = bankName;
}
public String getPayeeName() {
return payeeName;
}
public void setPayeeName(String payeeName) {
this.payeeName = payeeName;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getIfsCode() {
return ifsCode;
}
public void setIfscCode(String ifsCode) {
this.ifsCode = ifsCode;
}
public String getMicr() {
return micr;
}
public void setMicr(String micr) {
this.micr = micr;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
Below I am posting the method in which I am invoking a Python program and getting a Json response from it:
public class RunPython {
public static void main(String[] args) throws IOException,ScriptException,NullPointerException{
// TODO Auto-generated method stub
Process p = Runtime.getRuntime().exec("python <path to file>/reg.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line ;
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
} finally {
in.close();
}
ObjectMapper mapper = new ObjectMapper();
try {
Cheque cheque = mapper.readValue(line, Cheque.class);
System.out.println("Java object :");
System.out.println(cheque);
}
catch (JsonGenerationException ex) {
ex.printStackTrace();
}
catch (JsonMappingException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}}}
The JSON response which I am getting is:
{
"bankName": [
"Bank"
],
"accountNumber": [
"989898989898"
],
"ifsCode": [
"0000000"
],
"micr": [
"0000000"
],
"payeeName": [
"name"
]
}
After running the program I am getting the JSON response as expected, but while converting it to a Java object it is showing nullPointerException in the main thread. Help me out to find where I am making the mistake.

You consume/exhaust all your Process Inputstream here when printing it :
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
And later on when you call the below it's already null :
Cheque cheque = mapper.readValue(line, Cheque.class);
You'd have to process it in the above while loop, instead of only printing it out

When you reach the statement:
Cheque cheque = mapper.readValue(line, Cheque.class);
variable line is null.
So you can either rebuild the JSON string (with a StringBuilder), or remove the code that prints the response, and parse the JSON directly from p.getInputStream().

Your Java object has String value, but JSON has array type ([ ])

Related

Read JSON Nested element using reflection without using JsonFactory or ObjectMapper

[Unable to access property of another object stored in Arraylist]
I am creating an function to get JSON input in object from RESTful Web service input and format it again in JSON format to call other web service.
I have limitation that I can not use any JSON API for object mapping hence using Java reflection core API.
I am able to create JSON format from Input for simple elements but unable to access nested elements (another user defined POJO class ). I am using arraylist.
Input
{
"GenesisIncidents": {
"service": "Transmission",
"affectedCI": "22BT_ORNC03",
"opt_additionalAffectedItems": [
{
"itemType": "NODE-ID",
"ItemName": "22BT_ORNC03"
},
{
"ItemType": "CCT",
"ItemName": "A_circuit_id"
}]
}
}
GenesisIncidents.class
import java.util.ArrayList;
import java.util.Date;
public class GenesisIncidents {
private String service;
private String affectedCI;
private ArrayList<AdditionalAffectedItems> opt_additionalAffectedItems;
public GenesisIncidents(){}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getAffectedCI() {
return affectedCI;
}
public void setAffectedCI(String affectedCI) {
this.affectedCI = affectedCI;
}
public ArrayList<AdditionalAffectedItems> getOpt_additionalAffectedItems() {
return opt_additionalAffectedItems;
}
public void setOpt_additionalAffectedItems(ArrayList<AdditionalAffectedItems> opt_additionalAffectedItems) {
this.opt_additionalAffectedItems = opt_additionalAffectedItems;
}
}
AdditionalAffectedItems.class
public class AdditionalAffectedItems {
private String itemType;
private String itemName;
public AdditionalAffectedItems(){
super();
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
Implemetation
public void updateTicketExt(GenesisIncidents genesisIncidents) {
try{
Field allFields[]=genesisIncidents.getClass().getDeclaredFields();
Method allMethods[] = genesisIncidents.getClass().getDeclaredMethods();
String jsonString ="{\r\n \""+genesisIncidents.getClass().getName().toString().substring(48)+"\": {";
final String preStr="\r\n \""; //To create a JSON object format.
final String postStr="\": "; //To create a JSON object format.
int totalNoOfFields=allFields.length;
for (Field field : allFields) {
System.out.println(field.getType());
String getter="get"+StringUtils.capitalize(field.getName());
Method method= genesisIncidents.getClass().getMethod(getter, null);
try{
if(field.getType().toString().contains("Integer"))
jsonString=jsonString + preStr + field.getName() + postStr +method.invoke(genesisIncidents).toString()+",";
else
jsonString=jsonString + preStr + field.getName() + postStr +"\""+method.invoke(genesisIncidents).toString()+"\",";
if(field.getType().toString().contains("ArrayList")){
System.out.println("ArrayListElement found");
genesisIncidents.getOpt_additionalAffectedItems().forEach(obj->{System.out.println(obj.getItemName());});
//convertArrayToJSON(field, genesisIncidents);
}
}catch(NullPointerException npe)
{
System.out.println("Null value in field.");
continue;
}
}
jsonString=jsonString.substring(0,jsonString.length()-1);
jsonString=jsonString+"\r\n }\r\n }";
System.out.println("\n"+jsonString);
}catch(Exception jex){
jex.printStackTrace();
}
}
My below code line is unable to access object stored under array list.
genesisIncidents.getOpt_additionalAffectedItems().forEach(obj->{System.out.println(obj.getItemName());});
OUTPUT
karaf#root>class java.lang.String
class java.lang.String
class java.lang.String
class java.util.ArrayList
ArrayListElement found
null
null
{
"GenesisIncidents": {
"service": "Transmission",
"affectedCI": "22BT_ORNC03",
"opt_additionalAffectedItems": " [org.apache.servicemix.examples.camel.rest.model.AdditionalAffectedItems#5881a 895, org.apache.servicemix.examples.camel.rest.model.AdditionalAffectedItems#399b4e eb]"
}
}
I have fiddled around with your example I have managed to get it working. This will produce the correct JSON string by passing in an instance of a GenesisIncident object. I guess that there is much room for improvement here but this can serve as an example.
public static String genesisToJson(GenesisIncidents incidents) {
try{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{\r\n \"")
.append(incidents.getClass().getSimpleName())
.append("\": {");
Field allFields[] = incidents.getClass().getDeclaredFields();
for (Field field : allFields) {
String getter = getGetterMethod(field);
Method method = incidents.getClass().getMethod(getter, null);
try{
if(field.getType().isAssignableFrom(Integer.class)) {
jsonBuilder.append(preStr).append(field.getName()).append(postStr)
.append(method.invoke(incidents).toString()).append(",");
} else if (field.getType().isAssignableFrom(String.class)) {
jsonBuilder.append(preStr).append(field.getName()).append(postStr).append("\"")
.append(method.invoke(incidents).toString()).append("\",");
} else if (field.getType().isAssignableFrom(List.class)) {
System.out.println("ArrayListElement found");
getInnerObjectToJson(field, incidents.getOptItems(), jsonBuilder);
}
} catch(NullPointerException npe) {
System.out.println("Null value in field.");
continue;
}
}
jsonBuilder.append("\r\n } \r\n }");
return jsonBuilder.toString();
}catch(Exception jex){
jex.printStackTrace();
}
return null;
}
private static void getInnerObjectToJson(Field field, List<AdditionalAffectedItems> items, StringBuilder builder)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
builder.append(preStr).append(field.getName()).append(postStr).append("[");
for (var item : items) {
var fields = List.of(item.getClass().getDeclaredFields());
builder.append("{");
for (var f : fields) {
String getter = getGetterMethod(f);
Method method = item.getClass().getMethod(getter, null);
builder.append(preStr).append(f.getName()).append(postStr).append("\"")
.append(method.invoke(item).toString()).append("\"");
if (!(fields.indexOf(f) == (fields.size() - 1))) {
builder.append(",");
}
}
if (items.indexOf(item) == (items.size() - 1)) {
builder.append("}\r\n");
} else {
builder.append("},\r\n");
}
}
builder.append("]");
}
private static String getGetterMethod(Field field) {
return "get" + StringUtils.capitalize(field.getName());
}

Location is always null when reading an event

So I'm working on a Ticketing System but for some reason I can't seem to get a location in my events.
The TicketingSystem class has some hashmaps where I add my data to.
It also has reader methods the one I'm having trouble with is readEvents().
public TicketSystem() {
queueService = new QueueService();
users = new HashMap<>();
locations = new HashMap<>();
events = new HashMap<>();
readData();
}
public void addLocation(Venue location) {
locations.put(location.getId(), location);
}
public void addEvent(Event event) {
events.put(event.getId(), event);
}
public static Event getEvent(String eventId) {
return events.get(eventId);
}
public static Venue getLocation(String locationId) {
return locations.get(locationId);
}
public void readLocations() {
try (BufferedReader reader = new BufferedReader(new FileReader("venuedata.txt"))) {
String line = "";
VenueMapper mapper = new VenueMapper();
while ((line = reader.readLine()) != null) {
Venue venue = mapper.map(line.split(";"));
locations.put(venue.getId(), venue);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readEvents() {
try (BufferedReader reader = new BufferedReader(new FileReader("eventdata.txt"))) {
String line = "";
EventMapper mapper = new EventMapper();
while ((line = reader.readLine()) != null) {
Event event = mapper.map(line.split(";"));
events.put(event.getId(), event);
reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readData() {
readEvents();
readLocations();
}
With an EventMapper class which reads data from a text file through the TicketingSystem class split by ";" data[5] is my locationId.
#Override
public Event map(String[] data) {
String dateAndTime = data[1];
StringBuilder date = new StringBuilder(dateAndTime.substring(0, 8));
StringBuilder time = new StringBuilder(dateAndTime.substring(8));
return new Event(data[0], data[2], date.toString(), time.toString(), data[3], Double.parseDouble(data[4]), data[5]);
}
}
This is my event class which contains the constructor I'm using returning the event in the EventMapper class
public Event(String id, String name, String date, String time, String description,
double price, String locationId) {
this(name, LocalDate.parse(date, DateTimeFormatter.ofPattern("ddMMyyyy")),
LocalTime.parse(time, DateTimeFormatter.ofPattern("HHmm")), description, price);
this.id = id;
*setLocation(TicketSystem.getLocation(locationId));*
}
public void setLocation(Venue location) {
this.location = location;
}
Everytime I debug there's data in the locations list but for some reason my events aren't picking up the locations I'm trying to get.

How to Parse JSON object from a REST ENDPOINT?

I want to parse a JSON object from an endpoint (this one here: https://api.coinmarketcap.com/v1/ticker/bitcoin/) and store the value in a variable at a specific attribute, which in this case is the name.
This the ERROR i get:
java.lang.IllegalStateException: Expected a name but was STRING...
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// All your networking logic
// should be here
try {
String u = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
URL coinMarketCapApi = new URL(u);
HttpsURLConnection myConnection = (HttpsURLConnection) coinMarketCapApi.openConnection();
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
if (myConnection.getResponseCode() == 200) {
// Success
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginArray();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("name")) {
String value = jsonReader.nextName();
break; // Break out of the loop
} else {
jsonReader.skipValue();
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
you can convert the InputStream to String and then Create JSONArray from that string. like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
JSONArray jsonarray = new JSONArray(theString);
This way you don't have to manually construct the array.
Use this depandency for JSONArray
https://mvnrepository.com/artifact/org.json/json
You can fix the problem using gson.
https://github.com/google/gson
com.google.gson.stream.JsonReader jsonReader =
new com.google.gson.stream.JsonReader(new InputStreamReader(responseBody));
ArrayList<Coin> coins = new Gson().fromJson(jsonReader, Coin.class);
coins.forEach(coin -> System.out.println(coin.name));
public class Coin{
private String id;
private String name;
private String symbol;
private int rank;
#SerializedName("price_usd")
private double priceUsd;
...........
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public int getRank() {
return rank;
}
public double getPriceUsd() {
return priceUsd;
}
..........
}

Get User online/offline state

I have chat app where i need to develop user online state and for this i am calling API in every 15 seconds on server, which will return all logged in users and their online state in 0(Offline) and 1(Online).
I need to show whether user is online or offline (leaves app not logged out) while chatting.I have 1 array list which shows when app is launch with all logged in user id and their details including their online state and i created second API which return users online state in JSON.I have following option to achieve users online state
Replace existing array list item:-I am getting User ID and their online state in JSON but i need to run loop in every 15 second which replace values in existing arraylist
Store JSON in someway where i can easily find user id and its state:- If i store JSON in array list i need to run loop to find ID and its state which i dont want to,So which is best way to store JSON so i can easily get user state by its User ID.
Here is how i am getting JSON
protected List<WrapperClass> doInBackground(Void... params) {
userSession=new UserSession(context,"Elaxer");
UserState_Update=new ArrayList<>();
String data = null;
try {
String ID=userSession.getUserID(); //Getting Value from shared pref
data = URLEncoder.encode("User_ID", "UTF-8") + "=" + URLEncoder.encode(ID, "UTF-8");
Log.d(TAG,"Login ID "+ ID);
Log.d(TAG,"DO IN BACKGROUND START ");
URL url=new URL(URL_Path_NearBy);
connection= (HttpURLConnection) url.openConnection();
Log.d(TAG,connection.toString());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
//For POST Only - Begin
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
os.close();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG,"GET INPUT STREAM AND PUUTING INTO READER");
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
Log.d(TAG,"JSON ARRAY START");
JSONObject parentArray=new JSONObject(completeJSON);
JSONArray jsonArray=parentArray.getJSONArray("uData");
String LastSeen;
int LoginStatus,User_ID;
int Rec_Online_Status;
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject childObject=jsonArray.getJSONObject(i);
LastSeen=childObject.getString("lastseen") ;
LoginStatus=childObject.getInt("login_status") ;
User_ID=childObject.getInt("User_ID");
String UseID= String.valueOf(User_ID);
Log.d(TAG,"JSON Values "+LastSeen+" "+LoginStatus+" "+User_ID);
WrapperClass wrapperClass=new WrapperClass(UseID,LoginStatus);
UserState_Update.add(wrapperClass);
}
return UserState_Update; //List<WrapperClass> UserState_Update
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the response as JSON
{
"status": "SUCCESS",
"uData": [
{
"User_ID": "4",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "1",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "12",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "33",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
}
]
}
Is this right way to get user online state? (I know FCM is right way but FCM currently not ready on app server side)
UPDATE 2:-As code recommended by #XngPro i implement on doinBackground
Map<String,Online_Status_Wrapper.User> map=new HashMap<>();
Online_Status_Wrapper wrapper=gson.fromJson(completeJSON,Online_Status_Wrapper.class);
Log.d(TAG,"Wrapper Get Data value "+wrapper.getuData());
Log.d(TAG,"Wrapper Get Status value "+wrapper.getStatus());
for (Online_Status_Wrapper.User u: wrapper.getuData()){
map.put(u.getUser_ID(),u);
}
Log.d(TAG,"State of Other User users "+map.get(12).getLogin_status());//HERE I AM GETTING NullPointerException
return map;
I think you should use a Java serialization/deserialization library like Gson.
Hope to help you~
Example
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: 12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
public class Test {
public static void main(String[] args) {
bar();
}
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: " + "12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
}
Print

Jackson JSON array accessing

I have a Json file like this:
[{
dname: "xxxx",
dage: "24"
}, {
dname: "yyyy",
dage: "26"
}]
Target:
I want to access them as an array
Search through the names in the JSON file to look for a particular name
Same for age.
What I did:
file name : DtExtract.java
public class DtExtract{
public static ObjectMapper mapper = new ObjectMapper();
private Dtmain[] dtmain =mapper.readValue(new File("file location"), TypeFactory.defaultInstance().constructArrayType(D tmain.class));
public DtExtract() throws IOException{}
public String getname(int i) throws IOException { String strname = dtmain[i].getjname(); return strname;}
public String getage(int i) throws IOException { String strage = dtmain[i].getjage(); return strage;}
}
class Dtmain {
private String dname;
private String dage;
public Dtmain(){}
public String getjname(){return dname;}
public String getjage(){return dage;}
public void setjname(String dname){ this.dname=dname;}
public void setjage(String dage){ this.dage=dage;}
public String toString(){ return "Student [ name" + dname +", age " +dage +"]";
}
============================
file name: Myclass.java
public class Myclass{
public static void main(String args[]) throws IOException {
DtExtract dtextract= new DtExtract();
for(int i=0; i< 2; i++)
{
if (dtextract.getname(i).equals("xxxx")) {System.out.print("Name matches");}
if (dtextract.getage(i).equals("24")) {System.out.print("Age matches");}
}
}
}
=============================
This is the abstract of a code that I have, but my question is:
Does this for loop is really accessing the JSON array elements?
Is there any other faster way to do this JSON parsing and comparison?
You can do it as follows. You need to call both methods from main method
Please note that I have added two methods to process the array. processJsonArrayJava8 will be faster compared to processJsonArrayJava7.
public List<Dtmain> readFromJson()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Dtmain>> mapType = new TypeReference<List<Dtmain>>() {};
List<Dtmain> jsonList = mapper.readValue(
"[{\"dname\": \"xxxx\",\"dage\": \"24\" },{\"dname\": \"yyyy\",\"dage\": \"26\" }]",
mapType);
return jsonList;
}
public void processJsonArrayJava7(List<Dtmain> jsonList) {
for(Dtmain obj : jsonList) {
// do what ever you want with obj
}
}
public void processJsonArrayJava8(List<Dtmain> jsonList) {
jsonList.parallelStream().forEach(obj->{
//do what ever you want with obj
});
}
Please also give better names to the methods.
public class SayHi {
public static void main(String args[]) throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Person>> maptype = new TypeReference<List<Person>>() {};
List<Person> jsonTopersonList=mapper.readValue(new File("JSON_file_location"), maptype);
for(int i=0; i<jsonTopersonList.size(); i++){
System.out.println("Name"+i+":"+jsonTopersonList.get(i).dname);
}
for(int i=0; i<jsonTopersonList.size(); i++){
System.out.println("Age"+i+":"+jsonTopersonList.get(i).dage);
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class Person {
public String dname;
public int dage;
public Person() {
}
public Person(String dname,
int dage) {
this.dname = dname;
this.dage = dage;
}
public String toString() {
return "[" + dname + " " + dage +"]";
}
}
I came up with this one to deserialize that json data.

Categories