Chatbot problems - java

For some reasons i get null pointer errors in the code down. I'm working with a book of examples and trying to make smth mine, but seems like theres a change in java or mistake in book.
I'm making a Chatbot(sort of AI) and can't get it working in java. When i run the program it lets me only write Hi and then it replays.
When i try to give him another word like engi he acts like i always say hi.
If i restart and write first engi, then the error pops up, null pointer for some reason.
Can anyone help?
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.client.ClientProtocolException;
import com.google.gson.*;
public class engibot
{
JsonObject context;
public static void main (String[] args) {
engibot c= new engibot();
Scanner scanner= new Scanner(System.in);
String userUtterance;
do {
System.out.print("User:");
userUtterance=scanner.nextLine();
//end conversation
if (userUtterance.equals("QUIT")) {break;}
JsonObject userInput=new JsonObject();
userInput.add("userUtterance", new JsonPrimitive(userUtterance));
JsonObject botOutput = c.process(userInput);
String botUtterance = "";
if(botOutput !=null && botOutput.has("botUtterance")) {
botUtterance = botOutput.get("botUtterance").getAsString();
}
System.out.println("Bot:" + botUtterance);
}while(true);
scanner.close();
}
public engibot() {
context =new JsonObject();
}
public JsonObject process(JsonObject userInput) {
//step 1: process user input
JsonObject userAction = processUserInput(userInput);
//step 2: update context
updateContext(userAction);
//step 3: identify bot intent
identifyBotIntent();
//step 4: structure output
JsonObject out = getBotOutput();
return out;
}
public JsonObject processUserInput(JsonObject userInput) {
String userUtterance = null;
JsonObject userAction = new JsonObject();
//default case
userAction.add("userIntent", new JsonPrimitive(""));
if(userInput.has("userUtterance")) {
userUtterance= userInput.get("userUtterance").getAsString();
userUtterance=userUtterance.replaceAll("%2C", ",");
}
if (userUtterance.matches("(hi)|(hi | hello)( there)?")) {
userAction.add("userIntent", new JsonPrimitive("greet"));
}
else if (userUtterance.matches("(thanks)|(thank you)")) {
userAction.add("userIntent", new JsonPrimitive("thank"));
}
else if(userUtterance.matches("(engi) | (engagment)")) {
userAction.add("userIntent", new JsonPrimitive("request_engi"));
}
else {
//contextual processing
String currentTask = context.get("currentTask").getAsString();
String botIntent = context.get("botIntent").getAsString();
if(currentTask.equals("requestEngi") && botIntent.equals("requestUserName")) {
userAction.add("userIntent", new JsonPrimitive("inform_name"));
userAction.add("userName", new JsonPrimitive(userUtterance));
}
}
return userAction;
}
public void updateContext(JsonObject userAction) {
//copy userIntent
context.add("userIntent", userAction.get("userIntent"));
String userIntent = context.get("userIntent").getAsString();
if(userIntent.equals("greet")) {
context.add("currentTask", new JsonPrimitive("greetUser"));
}else if (userIntent.equals("request_engi")) {
context.add("currentTask", new JsonPrimitive("requestEngi"));
}else if (userIntent.equals("infrom_city")) {
String userName = userAction.get("userName").getAsString();
Engi userInfo = DB.getUserInfo(userName);
if(!userInfo.get("userName").isJsonNull()) {
context.add("placeOfWeather", userInfo.get("cityCode"));
context.add("placeName", userInfo.get("cityName"));
}
}else if (userIntent.equals("thank")) {
context.add("currenTask", new JsonPrimitive("thankUser"));
}
}
public void identifyBotIntent() {
String currentTask = context.get("currentTask").getAsString();
if(currentTask.equals("greetUser")) {
context.add("botIntent", new JsonPrimitive("greetUser"));
}else if(currentTask.equals("thankUser")) {
context.add("botIntent", new JsonPrimitive("thankUser"));
}else if (currentTask.equals("requestEngi")) {
if (context.get("userName").getAsString().equals("unknown")) {
context.add("botIntent", new JsonPrimitive("requestUserName"));
}
else {
Integer time = -1;
if (context.get("").getAsString().equals("current")) {
time=0;
}
Engi userReport =null;
userReport = DB.getUserInfo(
context.get("userName").getAsString());
if(userReport !=null) {
context.add("userReport", new JsonPrimitive("userReport"));
context.add("botIntent", new JsonPrimitive("informUser"));
}
}
}else {
context.add("botIntent", null);
}
}
public JsonObject getBotOutput() {
JsonObject out=new JsonObject();
String botIntent = context.get("botIntent").getAsString();
String botUtterance="";
if(botIntent.equals("greetUser")) {
botUtterance= "Hi there! I am EngiMan, your engagement bot! " + "What would you like to do? Engage someone or something else?";
}else if(botIntent.equals("thankUser")) {
botUtterance="Thanks for talking to me! Have a great day!!";
}else if (botIntent.equals("requestName")) {
botUtterance="Ok. What's his name?";
}else if(botIntent.equals("informUser")) {
String userDescription= getUserDescription(context.get("userName").getAsString());
String engiIndex= getEngiIndex();
botUtterance = "Ok. "+"Engagment index of "+userDescription+" is"+engiIndex+".";
}
out.add("botIntent", context.get("botIntent"));
out.add("botUtterance", new JsonPrimitive(botUtterance));
return out;
}
private String getEngiIndex() {
return context.get("engiIndex").getAsString();
}
private String getUserDescription(String userName) {
if (userName.equals("current")) {
return "current";
}
return null;
}
}
import com.google.gson.JsonElement;
public class Engi {
private String Name;
private String LastName;
private int Age;
private double EngiIndex;
private String Firm;
private String Team;
public JsonElement get(String string) {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lasteName) {
LastName = lasteName;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public double getEngiIndex() {
return EngiIndex;
}
public void setEngiIndex(double engiIndex) {
EngiIndex = engiIndex;
}
public String getFirm() {
return Firm;
}
public void setFirm(String firm) {
Firm = firm;
}
public String getTeam() {
return Team;
}
public void setTeam(String team) {
Team = team;
}
}

Related

json data should be print in specified textview

I have json data regarding student details,That i want to print in respective textviews. i'm new to json services please help me to print the this data on screen.I'm using getters and setters for subject score so further i want to use them dynamically.
here is my json data
{
"studentInfo": {
"studentName": "srini#gmail.com",
"studentId": "abc",
"date": 14102017,
"JanuaryScoreCard" : {
"english" : "44",
"Science" : "45",
"maths": "66",
"social" : "56",
"hindi" : "67",
"kannada" : "78",
},
"MarchScoreCard" : {
" english " : "54",
" Science " : "56",
" maths ": "70",
" social " : "87",
" hindi " : "98",
" kannada " : "56"
},
"comments" : ""
}
I'm Something to print but could not,i don't where i'm going wrong
public void init()
{
try {
parseJSON();
} catch (JSONException e)
{
e.printStackTrace();
}
}
public void parseJSON() throws JSONException{
jsonObject = new JSONObject(strJson);
JSONObject object = jsonObject.getJSONObject("studentInfo");
patientName = object.getString("studentName");
patientID = object.getString("studentId");
mName.setText(studentName);
mUserId.setText(studentId);
}
You can use JSON parser and then you can print any data you want from that,
Use GSON for this, here is an example https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Here is a basic JSON Parsing process
public void parseJson() {
String your_response = "replace this with your response";
try {
JSONObject jsonObject = new JSONObject(your_response);
JSONObject studentInfoJsonObject = jsonObject.getJSONObject("studentInfo");
StudentInfo studentInfo1 = new StudentInfo();
studentInfo1.setStudentName(studentInfoJsonObject.optString("studentName"));
studentInfo1.setStudentId(studentInfoJsonObject.optString("studentId"));
studentInfo1.setDate(studentInfoJsonObject.optString("date"));
studentInfo1.setComments(studentInfoJsonObject.optString("comments"));
JSONObject januaryScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
JanuaryScoreCard januaryScoreCard1 = new JanuaryScoreCard();
januaryScoreCard1.setEnglish(januaryScoreCardJsonObject.optString("english"));
januaryScoreCard1.setHindi(januaryScoreCardJsonObject.optString("hindi"));
januaryScoreCard1.setMaths(januaryScoreCardJsonObject.optString("maths"));
januaryScoreCard1.setSocial(januaryScoreCardJsonObject.optString("social"));
januaryScoreCard1.setKannada(januaryScoreCardJsonObject.optString("kannada"));
januaryScoreCard1.setScience(januaryScoreCardJsonObject.optString("Science"));
JSONObject marchScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
MarchScoreCard marchScoreCard = new MarchScoreCard();
marchScoreCard.setEnglish(marchScoreCardJsonObject.optString("english"));
marchScoreCard.setHindi(marchScoreCardJsonObject.optString("hindi"));
marchScoreCard.setMaths(marchScoreCardJsonObject.optString("maths"));
marchScoreCard.setSocial(marchScoreCardJsonObject.optString("social"));
marchScoreCard.setKannada(marchScoreCardJsonObject.optString("kannada"));
marchScoreCard.setScience(marchScoreCardJsonObject.optString("Science"));
studentInfo1.setJanuaryScoreCard(januaryScoreCard1);
studentInfo1.setMarchScoreCard(marchScoreCard);
} catch (JSONException e) {
e.printStackTrace();
}
}
Student Info Class
public class StudentInfo {
private String studentName;
private String studentId;
private String date;
private String comments;
private JanuaryScoreCard januaryScoreCard;
private MarchScoreCard marchScoreCard;
public JanuaryScoreCard getJanuaryScoreCard() {
return januaryScoreCard;
}
public void setJanuaryScoreCard(JanuaryScoreCard januaryScoreCard) {
this.januaryScoreCard = januaryScoreCard;
}
public MarchScoreCard getMarchScoreCard() {
return marchScoreCard;
}
public void setMarchScoreCard(MarchScoreCard marchScoreCard) {
this.marchScoreCard = marchScoreCard;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
and Here is January class
public class JanuaryScoreCard {
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
and Here is March Class
public class MarchScoreCard{
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
You need to parse this json Data , For this you need Create appropriate bean classes and put data while parsing json into this bean classes object and create List .
Then you need to create ListView and Adapter for populate data into Screen or Activity.

Java - Why stackoverflow error in my JSON method?

I need your help to understand why in my method the object allocation returns Stack Overflow error.
Here is the method:
public String toJson(){
JSONObject json;
json = new JSONObject(this); //error happens here...
return json.toString();
}
Here all code from this class:
package com.neocloud.model;
import java.io.Serializable;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.DeviceDAO;
import com.neocloud.model.dao.GroupDAO;
import com.neocloud.model.dao.SubscriptionDAO;
public class Subscription implements Serializable{
private static final long serialVersionUID = -3901714994276495605L;
private long id;
private Device dispositivo;
private Group grupo;
private String subscription;
public Subscription(){
clear();
}
public void clear(){
id = 0;
subscription = "";
grupo = new Group();
dispositivo = new Device();
}
public String toJson(){
JSONObject json;
json = new JSONObject(this); //error happens here...
return json.toString();
}
public String registerDB(boolean registrarSNS){
GroupDAO gDAO = new GroupDAO();
DeviceDAO dDAO = new DeviceDAO();
gDAO.selectById(this.grupo);
dDAO.selectById(this.dispositivo);
if (registrarSNS)
registerSNS(this.dispositivo.getEndPointArn(), this.grupo.getTopicArn());
SubscriptionDAO sDAO = new SubscriptionDAO();
return sDAO.insert(this);
}
public String registerSNS(String endpointArn, String topicArn){
String resposta;
AwsSns sns = AwsSns.getInstance();
resposta = ""+sns.addSubscriptionToTopic(endpointArn, topicArn);
setSubscription(resposta);
return resposta;
}
public String delete(){
AwsSns sns = AwsSns.getInstance();
SubscriptionDAO sDAO = new SubscriptionDAO();
sDAO.selectById(this);
sns.deleteSubscriptionFromTopic(this.subscription);
return sDAO.delete(this);
}
public long getId() {
return id;
}
public void setId(long id) {
if (this.id != id)
this.id = id;
}
public String getSubscription() {
return subscription;
}
public void setSubscription(String subscription) {
if (subscription != null){
if (!this.subscription.equals(subscription))
this.subscription = subscription;
}else
this.subscription = new String();
}
public Device getDispositivo() {
return dispositivo;
}
public void setDispositivo(Device dispositivo) {
if (dispositivo != null){
if (dispositivo.getId() != this.dispositivo.getId())
this.dispositivo = dispositivo;
}else
this.dispositivo = new Device();
}
public Group getGrupo() {
return grupo;
}
public void setGrupo(Group grupo) {
if (grupo != null){
if (grupo.getId() != this.grupo.getId())
this.grupo = grupo;
}else
this.grupo = new Group();
}
}
Here is the Device class:
package com.neocloud.model;
import java.io.Serializable;
import java.util.ArrayList;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.DeviceDAO;
import com.neocloud.model.enums.EEnvironment;
import com.neocloud.model.enums.EProduct;
import com.neocloud.model.enums.ESystem;
public class Device implements Serializable{
private static final long serialVersionUID = 8515474788917476721L;
private long id;
private String development;
private String SSL = "tls://gateway.push.apple.com:2195";
private String feedback = "tls://feedback.push.apple.com:2196";
private String sandboxSSL = "tls://gateway.sandbox.push.apple.com:2195";
private String sandboxFeedback = "tls://feedback.sandbox.push.apple.com:2196";
private String message;
private String endPointArn;
private String deviceToken;
private EProduct appID;
private String appVersion;
private String deviceUID;
private String deviceName;
private String deviceModel;
private String deviceVersion;
private boolean pushBadge;
private boolean pushAlert;
private boolean pushSound;
private ESystem system;
private EEnvironment environment;
private ArrayList<Subscription> subscriptions;
private String deviceUser;
public Device(){
clear();
}
public String deleteToken(){
/*
*
* terminar aqui ainda...
*
DeviceDAO dDAO = new DeviceDAO();
AwsSns sns = AwsSns.getInstance();
sns.deleteDeviceEndpoint(getEndPointArn());
ArrayList<String> subscriptions = dDAO.getSubscriptionsFromEndpointArn(this);
for (int i=0; i<subscriptions.size();i++){
sns.deleteSubscriptionFromTopic(subscriptions.get(i));
}
return dDAO.delete(this);
*/ return "";
}
public String updateToken(){
if ((system == ESystem.IOS) && (deviceToken.length() != 64))
return "deviceTokenlen64";
AwsSns sns = AwsSns.getInstance();
String jsonResposta = ""+sns.updateDeviceEndpoint(getEndPointArn(), deviceToken);
DeviceDAO dDAO = new DeviceDAO();
dDAO.update(this);
return jsonResposta;
}
public String registerDevice(){
if (appVersion.length() == 0)
return "applen0";
if (deviceUID.length() > 40)
return "deviceUID40";
if ((system == ESystem.IOS) && (deviceToken.length() != 64))
return "deviceTokenlen64";
if (deviceName.length() == 0)
return "deviceNamelen0";
if (deviceModel.length() == 0)
return "deviceModellen0";
if (deviceVersion.length() == 0)
return "deviceVersionlen0";
AwsSns sns = AwsSns.getInstance();
String jsonResposta = null;
switch (getAppID()) {
case MODULE: {
if (system == ESystem.IOS)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTMODULEIOS);
else if (system == ESystem.ANDROID)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTMODULEANDROID);
break;
}
case HOSTPRO: {
if (system == ESystem.IOS)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTHOSTPROIOS);
else if (system == ESystem.ANDROID)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTHOSTPROANDROID);
break;
}
case CONNEXOON: {
if (system == ESystem.IOS)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTCONNEXOONIOS);
else if (system == ESystem.ANDROID)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTCONNEXOONANDROID);
break;
}
case TAHOMA: {
break;
}
case MINIBOX: {
break;
}
case NONE: {
}
default: {
}
}
if (jsonResposta != null){
JSONObject json;
try {
jsonResposta = jsonResposta.replace("}", "\"}").replace("arn", "\"arn");
jsonResposta = jsonResposta.replace("{EndPointArn:", "{\"EndPointArn\":");
json = new JSONObject(jsonResposta);
setEndPointArn(json.getString("EndpointArn"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Subscription subscription;
switch (getAppID()){
case MODULE: {
subscription = new Subscription();
subscription.getGrupo().setId(19);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEGERAL);
subscriptions.add(subscription);
if (system == ESystem.IOS){
subscription = new Subscription();
subscription.getGrupo().setId(25);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEIOS);
subscriptions.add(subscription);
}
else if (system == ESystem.ANDROID){
subscription = new Subscription();
subscription.getGrupo().setId(22);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEANDROID);
subscriptions.add(subscription);
}
break;
}
case HOSTPRO: {
subscription = new Subscription();
subscription.getGrupo().setId(10);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROGERAL);
subscriptions.add(subscription);
if (system == ESystem.IOS){
subscription = new Subscription();
subscription.getGrupo().setId(16);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROIOS);
subscriptions.add(subscription);
}
else if (system == ESystem.ANDROID){
subscription = new Subscription();
subscription.getGrupo().setId(13);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROANDROID);
subscriptions.add(subscription);
}
break;
}
case CONNEXOON: {
subscription = new Subscription();
subscription.getGrupo().setId(1);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONGERAL);
subscriptions.add(subscription);
if (system == ESystem.IOS){
subscription = new Subscription();
subscription.getGrupo().setId(7);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONIOS);
subscriptions.add(subscription);
}
else if (system == ESystem.ANDROID){
subscription = new Subscription();
subscription.getGrupo().setId(4);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONANDROID);
subscriptions.add(subscription);
}
break;
}
case TAHOMA: {
break;
}
case MINIBOX: {
break;
}
case NONE: {
}
default: {
}
}
DeviceDAO dDAO = new DeviceDAO();
return dDAO.insert(this);
}
public void clear(){
development = "";
message = "";
endPointArn = "";
deviceToken = "";
appID = EProduct.NONE;
appVersion = "";
deviceUID = "";
deviceName = "";
deviceModel = "";
deviceVersion = "";
pushBadge = false;
pushAlert = false;
pushSound = false;
system = ESystem.NONE;
environment = EEnvironment.HOMOLOGATION;
subscriptions = new ArrayList<Subscription>();
deviceUser = "";
}
public String toJson(){
JSONObject json;
json = new JSONObject(this);
return json.toString();
}
public String getDevelopment() {
return development;
}
public void setDevelopment(String development) {
if (development != null){
if (!development.equals(this.development))
this.development = development;
}
this.development = new String();
}
public String getSSL() {
return SSL;
}
public void setSSL(String sSL) {
if (sSL != null){
if (!sSL.equals(this.SSL))
this.SSL = sSL;
}
else
this.SSL = new String();
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
if (feedback != null){
if (!feedback.equals(this.feedback))
this.feedback = feedback;
}
this.feedback = new String();
}
public String getSandboxSSL() {
return sandboxSSL;
}
public void setSandboxSSL(String sandboxSSL) {
if (sandboxSSL != null){
if (!sandboxSSL.equals(this.sandboxSSL))
this.sandboxSSL = sandboxSSL;
}else
this.sandboxSSL = new String();
}
public String getSandboxFeedback() {
return sandboxFeedback;
}
public void setSandboxFeedback(String sandboxFeedback) {
if (sandboxFeedback != null){
if (!sandboxFeedback.equals(this.sandboxFeedback))
this.sandboxFeedback = sandboxFeedback;
}else
this.sandboxFeedback = new String();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
if (message != null){
if (!message.equals(this.message))
this.message = message;
}else
this.message = new String();
}
public String getEndPointArn() {
return endPointArn;
}
public void setEndPointArn(String createPlatformEndpointResult) {
if (createPlatformEndpointResult != null){
if (!createPlatformEndpointResult.equals(this.endPointArn))
this.endPointArn = createPlatformEndpointResult;
}else
this.endPointArn = new String();
}
public String getDeviceToken() {
return deviceToken;
}
public void setDeviceToken(String deviceToken) {
if (deviceToken != null){
if (!deviceToken.equals(this.deviceToken))
this.deviceToken = deviceToken;
}else
this.deviceToken = new String();
}
public EProduct getAppID() {
return appID ;
}
public void setAppID(EProduct appID){
if (appID != this.appID)
this.appID = appID;
}
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String appVersion) {
if (appVersion != null){
if (!appVersion.equals(this.appVersion))
this.appVersion = appVersion;
}else
this.appVersion = new String();
}
public String getDeviceUID() {
return deviceUID;
}
public void setDeviceUID(String deviceUID) {
if (deviceUID != null){
if (!deviceUID.equals(this.deviceUID))
this.deviceUID = deviceUID;
}else
this.deviceUID = new String();
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
if (deviceName != null){
if (!deviceName.equals(this.deviceName))
this.deviceName = deviceName;
}else
this.deviceName = new String();
}
public String getDeviceModel() {
return deviceModel;
}
public void setDeviceModel(String deviceModel) {
if (deviceModel != null){
if (!deviceModel.equals(this.deviceModel))
this.deviceModel = deviceModel;
}else
this.deviceModel = new String();
}
public String getDeviceVersion() {
return deviceVersion;
}
public void setDeviceVersion(String deviceVersion) {
if (deviceVersion != null){
if (!deviceVersion.equals(this.deviceVersion))
this.deviceVersion = deviceVersion;
}else
this.deviceVersion = new String();
}
public boolean isPushBadge() {
return pushBadge;
}
public void setPushBadge(boolean pushBadge) {
if (pushBadge != this.pushBadge)
this.pushBadge = pushBadge;
}
public boolean isPushAlert() {
return pushAlert;
}
public void setPushAlert(boolean pushAlert) {
if (pushAlert != this.pushAlert)
this.pushAlert = pushAlert;
}
public boolean isPushSound() {
return pushSound;
}
public void setPushSound(boolean pushSound) {
if (this.pushSound != pushSound)
this.pushSound = pushSound;
}
public ESystem getSystem() {
return system;
}
public void setTipoSmartphone(ESystem system) {
if (system != this.system)
this.system = system;
}
public EEnvironment getEnvironment() {
return environment;
}
public void setEnvironment(EEnvironment environment) {
if (environment != this.environment)
this.environment = environment;
}
public long getId() {
return id;
}
public void setId(long id) {
if (this.id != id)
this.id = id;
}
public void setSystem(ESystem system) {
if (system != this.system)
this.system = system;
}
public ArrayList<Subscription> getSubscriptions() {
return subscriptions;
}
public void setSubscriptions(ArrayList<Subscription> subscriptions) {
if (subscriptions != null)
this.subscriptions = subscriptions;
else
this.subscriptions = new ArrayList<Subscription>();
}
public String getDeviceUser() {
return deviceUser;
}
public void setDeviceUser(String deviceUser) {
if (deviceUser != null){
if (!deviceUser.equals(this.deviceUser))
this.deviceUser = deviceUser;
}else
this.deviceUser = new String();
}
}
Here is the Group class:
package com.neocloud.model;
import java.io.Serializable;
import java.util.ArrayList;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.GroupDAO;
public class Group implements Serializable{
private static final long serialVersionUID = -5032857327241801763L;
private long id;
private String nome;
private String topicArn;
public Group(){
this.clear();
}
public void clear(){
this.id = 0;
this.nome = new String();
this.topicArn = new String();
}
public String registerGrupo(){
AwsSns snsClient = AwsSns.getInstance();
String topic = ""+snsClient.createTopic(this.nome);
JSONObject json;
String jsonResposta = topic;
try {
jsonResposta = jsonResposta.replace("}", "\"}").replace("arn", "\"arn");
jsonResposta = jsonResposta.replace("{TopicArn:", "{\"TopicArn\":");
json = new JSONObject(jsonResposta);
setTopicArn(json.getString("TopicArn"));
} catch (JSONException e) {
e.printStackTrace();
}
GroupDAO grupoDAO = new GroupDAO();
return grupoDAO.insert(this);
}
public String deleteGrupo(){
AwsSns snsClient = AwsSns.getInstance();
GroupDAO grupoDAO = new GroupDAO();
ArrayList<Group> grupos = grupoDAO.select(this);
if (grupos.size() > 0){
for (int i = 0; i<grupos.size(); i++){
this.topicArn = grupos.get(i).getTopicArn();
this.nome = grupos.get(i).getNome();
this.id = grupos.get(i).getId();
snsClient.deleteTopic(this.topicArn);
}
return grupoDAO.delete(this);
}
return "-1";
}
public String toJson(){
JSONObject json;
json = new JSONObject(this);
return json.toString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTopicArn() {
return topicArn;
}
public void setTopicArn(String topicArn) {
this.topicArn = topicArn;
}
}
Here is the Tomcat log:
Exception in thread "http-bio-8080-exec-5"
java.lang.StackOverflowError at
java.lang.reflect.Executable.(Unknown Source) at
java.lang.reflect.Method.(Unknown Source) at
java.lang.reflect.Method.copy(Unknown Source) at
java.lang.reflect.ReflectAccess.copyMethod(Unknown Source) at
sun.reflect.ReflectionFactory.copyMethod(Unknown Source) at
java.lang.Class.copyMethods(Unknown Source) at
java.lang.Class.getMethods(Unknown Source) at
com.amazonaws.util.json.JSONObject.populateMap(JSONObject.java:930)
at com.amazonaws.util.json.JSONObject.(JSONObject.java:285) at
com.amazonaws.util.json.JSONObject.wrap(JSONObject.java:1540) at
com.amazonaws.util.json.JSONObject.populateMap(JSONObject.java:960)
Thanks for all help!
Maybe a circular reference in your object.
json = new JSONObject(this);
You're trying to JSONify this
id = 0;
subscription = "";
grupo = new Group();
dispositivo = new Device();
And i think that somehow, it cant JSONify Group and Device. Could you show us the code for those classes ?
UPDATE : In your Subscription.clear() method, you affect a new Group() & a new Device(). When creating a new Device(), the method Device.clear() get called and create a new ArrayList<Subscription>(), that'll call the method Subscription.clear(), that'll affect a new Group() & a new Device() and so on. You're infinitely looping, that's why you get the StackOverflow error. It's weird that you're subscription is made of a Group that is made of an ArrayList of subscription who are also mades of Groups etc.
Maybe you have a circular reference...
Object a = X;
Object c = Y;
a.prop = Y;
c.prop2 = X;
then, your JSON(a) is
{
prop : {
prop2 : {
prop : Y (Y have prop2 again)
/*infinite..*/
}
}
}

Getting a whole event instead of a part in Java

Actually I have two probles. One of them is that I am getting empty fields in my RSS Reader. I get just:
screenshot
I was trying to found what's wrong with my code and I noticed that method which should read title, describtion and other stuff singly, its reading all of them together. I mean that my String which should have just single object like title, have everyting like: screenshot
And I have no idea why. Can you help me? I know that there's a lot of code but the problem is in reedFeed in RSSFeedParser class.
Main:
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Scanner;
/**
* Created by Maciek on 2015-11-12.
*/
public class ReadTest {
private static Scanner scanner = new Scanner(System.in);
private static RSSList rssList = new RSSList();
private static String url;
public static String righturl;
public static void main(String[] args) throws XMLStreamException, IOException, ClassNotFoundException {
MENU();
}
public static void MENU() throws IOException, ClassNotFoundException, XMLStreamException {
int choice;
System.out.println("MENU:");
System.out.println(" 1 = Wydrukuj RSS");
System.out.println(" 2 = Pokaz liste dodanych RSS");
System.out.println(" 3 = Dodaj link RSS");
System.out.println(" 4 = Usun link RSS");
System.out.println(" 5 = Wydrukuj historie");
System.out.println("5 = zakoncz");
choice = scanner.nextInt();
switch (choice) {
case 1:
rssList.readCurrentlyList();
printRSS();
MENU();
break;
case 2:
rssList.readCurrentlyList();
printList();
MENU();
break;
case 3:
rssList.readCurrentlyList();
rssList.readHistory();
feedURL();
checkCurrentyList();
rssList.saveCurrentlyList();
MENU();
break;
case 4:
rssList.readCurrentlyList();
System.out.println("Ktory link chcesz usunac?");
printList();
deleteIndex();
rssList.saveCurrentlyList();
MENU();
break;
case 5:
rssList.readHistory();
readHistory();
MENU();
break;
}
}
public static void printRSS() throws XMLStreamException {
for (int i = 0; i < rssList.RSSList.size(); i++) {
righturl = rssList.RSSList.get(i);
RSSFeedParser parser = new RSSFeedParser(righturl);
Feed feed = parser.readFeed();
System.out.println(feed);
for (FeedMessage message : feed.getMessages()) {
System.out.println(message);
}
}
}
public static void printList(){
for(int i = 0; i<rssList.RSSList.size(); i++){
System.out.println(i+1 +". "+rssList.RSSList.get(i));
}
}
public static void deleteIndex(){
int index = scanner.nextInt();
rssList.RSSList.remove(index-1);
}
public static void feedURL(){
scanner.nextLine();
url = scanner.nextLine();
}
public static void addToHistory(){
boolean thereAlreadyIs = false;
for(int i = 0; i<rssList.RSSHistory.size(); i++){
if(rssList.RSSHistory.get(i).equals(url)){
thereAlreadyIs = true;
}
}
if(thereAlreadyIs==false){
rssList.RSSHistory.add(url);
}
}
public static void checkCurrentyList() throws IOException, ClassNotFoundException {
boolean thereAlreadyIs = false;
rssList.readCurrentlyList();
for (int i = 0; i < rssList.RSSList.size(); i++) {
if (url.equals(rssList.RSSList.get(i))) {
thereAlreadyIs = true;
}
}
if (thereAlreadyIs == true) {
System.out.println("Juz jest dodany RSS o takim adresie!");
}
else{
addRSS();
}
}
public static void addRSS(){
rssList.RSSList.add(url);
addToHistory();
}
public static void readHistory() throws IOException, ClassNotFoundException {
rssList.readHistory();
for(int i =0; i<rssList.RSSHistory.size(); i++){
System.out.println("1. "+rssList.RSSHistory.get(i));
}
}
}
Class which collecting reader data.
import java.util.ArrayList;
import java.util.List;
/**
* Created by Maciek on 2015-11-11.
*/
public class Feed {
final String title;
final String description;
final String link;
final String language;
final String copyright;
final String pubDate;
final List<FeedMessage> entries = new ArrayList<FeedMessage>();
public Feed(String title, String description, String link, String language, String copyright, String pubDate){
this.title=title;
this.description=description;
this.link=link;
this.language=language;
this.copyright=copyright;
this.pubDate=pubDate;
}
public List<FeedMessage> getMessages(){
return entries;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
public String getLink(){
return link;
}
public String getLanguage(){
return language;
}
public String getCopyright(){
return copyright;
}
public String getPubDate(){
return pubDate;
}
public String toString(){
return "Freed: [Title: " +title+", Description: "+description+", Copyright: "+copyright+", Language: "+language+", PubDate: "+pubDate;
}
}
Class which is using to print RSS
public class FeedMessage {
String title;
String description;
String link;
String author;
String guid;
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
public void setDescription(String description){
this.description=description;
}
public String getDescription(){
return description;
}
public void setLink(String link){
this.link=link;
}
public String getLink(){
return link;
}
public void setAuthor(String author){
this.author=author;
}
public String getAuthor(){
return author;
}
public void setGuid(String guid){
this.guid=guid;
}
public String getGuid(){
return guid;
}
public String toString(){
return "FeedMessage: [title= "+title+", Description= "+description+", Link= "+link+", Author: "+author+", Guid= "+guid;
}
}
FeedParser class:
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Created by Maciek on 2015-11-15.
*/
public class RSSFeedParser {
public static final String ITEM = "item";
public static String description = "";
public static String title = "";
public static String link = "";
public static String language = "";
public static String copyright = "";
public static String author = "";
public static String pubDate = "";
public static String guid = "";
public Feed feed;
public boolean isFeedHeader;
public InputStream in;
public XMLInputFactory inputFactory = XMLInputFactory.newInstance();
public XMLEventReader eventReader;
public XMLEvent event;
final URL url;
TITLE tytul = new TITLE();
AUTHOR autor = new AUTHOR();
COPYRIGHT prawa = new COPYRIGHT();
DESCRIPTION opis = new DESCRIPTION();
GUID identyfikacja = new GUID();
LANGUAGE jezyk = new LANGUAGE();
LINK linskon = new LINK();
PUB_DATE publikajca = new PUB_DATE();
ITEM itemson = new ITEM();
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
in = read();
eventReader = inputFactory.createXMLEventReader(in);
event = eventReader.nextEvent();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() throws XMLStreamException {
try {
isFeedHeader = true;
event = eventReader.nextEvent();
while(eventReader.hasNext()) {
itemson.feedData(this);
tytul.feedData(this);
opis.feedData(this);
System.out.println(description);
linskon.feedData(this);
identyfikacja.feedData(this);
jezyk.feedData(this);
autor.feedData(this);
publikajca.feedData(this);
prawa.feedData(this);
eventReader.close();
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return feed;
}
public Feed setAllElements() throws XMLStreamException {
FeedMessage message = new FeedMessage();
message.setAuthor(author);
message.setDescription(description);
message.setGuid(guid);
message.setLink(link);
message.setTitle(title);
feed.getMessages().add(message);
return feed;
}
private InputStream read() throws XMLStreamException {
try {
return url.openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException {
String results = "";
if (event instanceof Characters) {
results = event.asCharacters().getData();
}
return results;
}
}
And I'll paste here just a one of classes which implements after:
public interface Case {
void feedData(RSSFeedParser rss) throws XMLStreamException;
}
Important class is ITEM:
public class ITEM implements Case {
#Override
public void feedData(RSSFeedParser rss) throws XMLStreamException {
if (rss.isFeedHeader) {
rss.isFeedHeader = false;
rss.feed = new Feed(rss.title, rss.link, rss.description, rss.language, rss.copyright, rss.pubDate);
}
rss.event = rss.eventReader.nextEvent();
if (rss.event.isEndElement()) {
if (rss.event.asEndElement().getName().getLocalPart() == (rss.ITEM)) {
try {
rss.setAllElements();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
}
}
and as I said one of these class:
for example title:
public class TITLE implements Case {
#Override
public void feedData(RSSFeedParser rss) throws XMLStreamException {
rss.title = rss.getCharacterData(rss.event, rss.eventReader);
rss.eventReader.close();
}
}
Thanks so much for every help!

How to access nested elements of json object using getJSONArray method

I have a JSON response that looks like this:
{
"result": {
"map": {
"entry": [
{
"key": { "#xsi.type": "xs:string", "$": "ContentA" },
"value": "fsdf"
},
{
"key": { "#xsi.type": "xs:string", "$": "ContentB" },
"value": "dfdf"
}
]
}
}
}
I want to access the value of the "entry" array object. I am trying to access:
RESPONSE_JSON_OBJECT.getJSONArray("entry");
I am getting JSONException. Can someone please help me get the JSON array from the above JSON response?
You have to decompose the full object to reach the entry array.
Assuming REPONSE_JSON_OBJECT is already a parsed JSONObject.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
Try this code using Gson library and get the things done.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);
I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonProgram {
public static void main(String... args) {
String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"#xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"#xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";
Gson gson = new GsonBuilder().serializeNulls().create();
Response res = gson.fromJson(response, Response.class);
System.out.println("Entries: " + res.getResult().getMap().getEntry());
}
}
class Response {
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
#Override
public String toString() {
return result.toString();
}
}
class Result {
private MapNode map;
public MapNode getMap() {
return map;
}
public void setMap(MapNode map) {
this.map = map;
}
#Override
public String toString() {
return map.toString();
}
}
class MapNode {
List<Entry> entry = new ArrayList<Entry>();
public List<Entry> getEntry() {
return entry;
}
public void setEntry(List<Entry> entry) {
this.entry = entry;
}
#Override
public String toString() {
return Arrays.toString(entry.toArray());
}
}
class Entry {
private Key key;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
#Override
public String toString() {
return "[key=" + key + ", value=" + value + "]";
}
}
class Key {
#SerializedName("$")
private String value;
#SerializedName("#xsi.type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "[value=" + value + ", type=" + type + "]";
}
}
Program output:
Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]
If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
You can try this:
JSONObject result = new JSONObject("Your string here").getJSONObject("result");
JSONObject map = result.getJSONObject("map");
JSONArray entries= map.getJSONArray("entry");
I hope this helps.
I'm also faced with this issue. So I solved with recursion. Maybe it will be helpfull.
I created method.I used org.json library.
public static JSONObject function(JSONObject obj, String keyMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
if you have questions, I can explain...
I would also try it this way
1) Create the Java Beans from the JSON schema
2) Use JSON parser libraries to avoid any sort of exception
3) Cast the parse result to the Java object that was created from the initial JSON schema.
Below is an example JSON Schema"
{
"USD" : {"15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68, "symbol" : "$"},
"JPY" : {"15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99, "symbol" : "¥"},
}
Code
public class Container {
private JPY JPY;
private USD USD;
public JPY getJPY ()
{
return JPY;
}
public void setJPY (JPY JPY)
{
this.JPY = JPY;
}
public USD getUSD ()
{
return USD;
}
public void setUSD (USD USD)
{
this.USD = USD;
}
#Override
public String toString()
{
return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
}
}
public class JPY
{
#SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
#Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class USD
{
#SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
#Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class MainMethd
{
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
// TODO Auto-generated method stub
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
String res = obj.toString();
Gson gson = new Gson();
Container container = new Container();
container = gson.fromJson(res, Container.class);
System.out.println(container.getUSD());
System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
}
}
Output from the main method is:
ClassPojo [15m = 478.68, symbol = $, last = 478.68, sell = 478.68, buy = 478.55]
Sell Price : $478.68
Buy Price : $478.55
Hope this helps.

JSON Parsing with GSON

I have the following Json string.How to parse this kind of Json using Gson in Java?Any help would be appreciated.
{
"acclst":[{
"accountInfoData":[{
"userId":9,
"rid":"1-Z5S3",
"acnme":"acc_1234.",
"actpe":"Fabricator / Distributor",
"mph":"2660016354",
"euse":"Biofuels",
"com":"0",
"sta":"Active",
"stem":"BBUSER5",
"wsite":"",
"fax":"",
"zone":"",
"crted":"BBUSER4",
"statusX":1,
"partyId":0,
"address":[]
}
]
}
],
"conlst":[],
"actlst":[],
"prolst":[],
"code":"200"
}
your Gson getter/Setter class will be
sample.java
public class sample {
public String code="";
ArrayList<String> conlst;
ArrayList<String> actlst;
ArrayList<innerObject> prolst;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ArrayList<String> getConlst() {
return conlst;
}
public void setConlst(ArrayList<String> conlst) {
this.conlst = conlst;
}
public ArrayList<String> getActlst() {
return actlst;
}
public void setActlst(ArrayList<String> actlst) {
this.actlst = actlst;
}
public ArrayList<innerObject> getProlst() {
return prolst;
}
public void setProlst(ArrayList<innerObject> prolst) {
this.prolst = prolst;
}
}
innerObject.java
public class innerObject {
ArrayList<String> accountInfoData;
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
secondInnerObject.java
public class secondInnerObject {
public String userId="";
public String rid="";
public String acme="";
public String actpe="";
public String mph="";
public String euse="";
public String com="";
public String sta="";
public String stem="";
public String wsite="";
public String fax="";
public String zone="";
public String crted="";
public String statusX="";
public String partyId="";
ArrayList<String> address;
ArrayList<String> accountInfoData;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getAcme() {
return acme;
}
public void setAcme(String acme) {
this.acme = acme;
}
public String getActpe() {
return actpe;
}
public void setActpe(String actpe) {
this.actpe = actpe;
}
public String getMph() {
return mph;
}
public void setMph(String mph) {
this.mph = mph;
}
public String getEuse() {
return euse;
}
public void setEuse(String euse) {
this.euse = euse;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public String getSta() {
return sta;
}
public void setSta(String sta) {
this.sta = sta;
}
public String getStem() {
return stem;
}
public void setStem(String stem) {
this.stem = stem;
}
public String getWsite() {
return wsite;
}
public void setWsite(String wsite) {
this.wsite = wsite;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getCrted() {
return crted;
}
public void setCrted(String crted) {
this.crted = crted;
}
public String getStatusX() {
return statusX;
}
public void setStatusX(String statusX) {
this.statusX = statusX;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public ArrayList<String> getAddress() {
return address;
}
public void setAddress(ArrayList<String> address) {
this.address = address;
}
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
to fetch
String json= "your_json_string";
Gson gson= new Gson();
sample objSample=gson.fromJson(json,sample.getClass());
thats it
You have to use JSONObject to parse this json in android.
Take a look at the following link.
http://developer.android.com/reference/org/json/JSONObject.html
Android already contains the required JSON libraries. You can use a valid string or a file for input. Here is code and explanation taken from here:
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";//write your JSON String here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
Here you have a tutorial which answers your needs - Android + Gson

Categories

Resources