Deserializing Gson NullPointer? - java

I am trying to parse JSON to get some values.
{
"username":"shobhit#gmail.com",
"roles:
{
"ROLE_Student_Trial":true,
"ROLE_student":true,
"ROLE_Student_Unlimited":true
},
"type":"student",
"lastLogin":1441305986000,
"token":"123"
}
This is how I am deSerializing it
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
String userName = obj.get("username").getAsString();
JsonObject roles = obj.get("roles").getAsJsonObject();
Boolean isTrial = roles.get("ROLE_Student_Trial").getAsBoolean();
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
Boolean isUnlimited = roles.get("ROLE_Student_Unlimited").getAsBoolean(); // LoginTest.java:31
long lastLogin = obj.get("lastLogin").getAsLong();
int token = obj.get("token").getAsInt();
String type = obj.get("type").getAsString();
System.out.println(userName);
if(isTrial){
System.out.println("Student trial is on last login " + timeConverter(lastLogin));
}
if(isStudent){
System.out.println("Student access level");
}
if(isUnlimited){
System.out.println("Student is unlimited as " + type + " and its token = " + token);
}
I was trying to get values of inner JSON,
but I am getting NullPointerException.
Exception in thread "main" java.lang.NullPointerException
at loginActivityHttpURL.LoginTest.main(LoginTest.java:31)

I am answering to my own question.
JSON is case sensitive, so at ("ROLE_Student") gson wouldn't find any value. Instead I corrected it with ("ROLE_student") and it worked.
Thanks to #Tobia Tesan

Change this line
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
to
Boolean isStudent = roles.get("ROLE_student").getAsBoolean();

Related

error when get value from marketdataincremental refresh

I got an error in my quickfixj Application. First, I got an error like this:
Out of order repeating group members
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
But now I got another error in my application:
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:38)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInThread$1(SingleThreadedEventHandlingStrategy.java:145)
at quickfix.mina.SingleThreadedEventHandlingStrategy$ThreadAdapter$RunnableWrapper.run(SingleThreadedEventHandlingStrategy.java:267)
at java.lang.Thread.run(Thread.java:748)
My code for get value of symbols is :
public void fromApp(quickfix.Message message, SessionID sessionID)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
try {
String symbol = message.getString(Symbol.FIELD);
System.out.println(" FromApp " + message);
message.getString(TransactTime.FIELD);
// String seqNo = message.getString(MsgSeqNum.FIELD);
double bid = message.getDouble(MDEntryPx.FIELD);
double ask = message.getDouble(MDEntryPx.FIELD);
// System.out.println(seqNo + " " + message);
} catch (FieldNotFound fieldNotFound) {
fieldNotFound.printStackTrace();
}
}
I have also using this code
public void onMessage (MarketDataIncrementalRefresh message, SessionID sessionID) throws FieldNotFound{
try
{
MDReqID mdreqid = new MDReqID();
SendingTime sendingtime = new SendingTime();
NoMDEntries nomdentries = new NoMDEntries();
quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries group
= new quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries();
MDUpdateAction mdupdateaction = new MDUpdateAction();
DeleteReason deletereason = new DeleteReason();
MDEntryType mdentrytype = new MDEntryType();
MDEntryID mdentryid = new MDEntryID();
Symbol symbol = new Symbol();
MDEntryOriginator mdentryoriginator = new MDEntryOriginator();
MDEntryPx mdentrypx = new MDEntryPx();
Currency currency = new Currency();
MDEntrySize mdentrysize = new MDEntrySize();
ExpireDate expiredate = new ExpireDate();
ExpireTime expiretime = new ExpireTime();
NumberOfOrders numberoforders = new NumberOfOrders();
MDEntryPositionNo mdentrypositionno = new MDEntryPositionNo();
message.getField(nomdentries);
message.getField(sendingtime);
message.getGroup(1, group);
int list = nomdentries.getValue();
for (int i = 0; i < list; i++)
{
message.getGroup(i + 1, group);
group.get(mdupdateaction);
if (mdupdateaction.getValue() == '2')
System.out.println("Enter");
group.get(deletereason);
group.get(mdentrytype);
group.get(mdentryid);
group.get(symbol);
group.get(mdentryoriginator);
if (mdupdateaction.getValue() == '0')
group.get(mdentrypx);
group.get(currency);
if (mdupdateaction.getValue() == '0')
group.get(mdentrysize);
}
System.out.printf("Got Symbol {0} Price {1}",
symbol.getValue(), mdentrypx.getValue());
}catch (Exception ex)
{
System.out.println("error" + ex);
}
but i also get error like this
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:39)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInpacket_write_wait: Connection to 3.13.235.241 port 22: Broken pipe
and here the value i check in my message.log
8=FIX.4.2^A9=0217^A35=X^A34=7291^A49=Fastmatch1^A52=20200401-10:47:59.833^A56=MDValueTrade2UAT1^A262=VT_020^A268=02^A279=2^A55=GBP/CHF^A269=0^A278=1140851192^A270=1.19503^A271=02000000^A279=0^A55=GBP/CHF^A269=0^A278=1140851194^A270=1.19502^A271=06000000^A10=114^A
my broker have send to me the price and etc
My question is: how to fix my problem from this code ?
First, I got an error like this:
Out of order repeating group members
Your data dictionary doesn't match your counterparty's. Fix that and this will go away.
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
This did not fix anything -- it HIDES your actual problem and has you looking at a new fake problem.
What you need to do:
Your configuration has this, right?
UseDataDictionary=Y
DataDictionary=path/to/FIXnn.xml
# or if FIX5:
AppDataDictionary=path/to/FIX5n.xml
TransportDataDictionary=path/to/FIXT.xml
Find your counterparty's documentation, and make sure your xml file's messages and fields match what they say they're going to send you. Make sure all repeating groups have the same fields in the same order.
Here is some documentation about how the Data Dictionary xml file is structured. It's pretty easy.

usertype value showing null in android

Hi In This code I am getting response by using json for that created one map in that I mention key and value.Now That value storing in one variable for that I wrote like this
String usertype = usertypeMap.get(user_type[i]);
But The usertype showing null can any one please help me where I did mistake.
java
String username1 = usname.getText().toString();
String password = pword.getText().toString();
queryString = "username=" + username1 + "&password="
+ password ;
String user_type1 = DatabaseUtility.executeQueryPhp("usertype",queryString);
System.out.print(user_type1);
try
{
JSONArray JA = new JSONArray(user_type1);
username = new String[JA.length()];
user_type = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
username[i] = JA.getJSONObject(i).getString("username");
user_type[i] = JA.getJSONObject(i).getString("user_type");
usertypeMap.put(username[i],user_type[i]);
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
e.printStackTrace();
}
String usertype = usertypeMap.get(user_type[i]);
try{
queryString = "username=" + username1 + "&password="
+ password +"&user_type="+usertype;
final String data = DatabaseUtility.executeQueryPhp("login",queryString);
You are getting value from the value
Map is(KEY,VALUE). In your code, key is username[i] value is user_type[i]. But you getting the value like this
String usertype = usertypeMap.get(user_type[i]);
try using like this
String usertype = usertypeMap.get(username[i]);

What is wrong with this VenuesExplore?

I am trying to get Venue names from the following codes but keep getting errors. Its obvious the snippet has some logical errors. How do I get it to display data?
String callbackUrl = "https://developer.foursquare.com/docs/samples/explore?client_id=6666666&v=20140101&ll=43,-79&client_secret=55555555";
FoursquareApi foursquareApi = new FoursquareApi(clientId, client_Secret, callbackUrl);
Result<Recommended> result = foursquareApi.venuesExplore(ll, null, null, null, null,null,query, null, null);
if (result.getMeta().getCode() == 200)
{
for (RecommendationGroup venue : result.getResult().getGroups())
{
for(Recommendation r: venue.getItems())
{
CompactVenue cmp = r.getVenue();
System.out.println(cmp.getName());
}
}
}
else
{
System.out.println("Error occured: ");
System.out.println(" code: " + result.getMeta().getCode());
System.out.println(" type: " + result.getMeta().getErrorType());
System.out.println(" detail: " + result.getMeta().getErrorDetail());
}
Nothing is displayed when the program is run. So I guess its logical error.
I had the same error.
For me it helped to change the venuesExplore() Method of the FoursquareApi.
public Result<Recommended> venuesExplore(String ll, Double llAcc, Double alt, Double altAcc, Integer radius, String section, String query, Integer limit, String basis) throws FoursquareApiException {..}
It seems that there is something wrong with the json parsing of the keywords.
So I changed the:
KeywordGroup keywords = (KeywordGroup) JSONFieldParser.parseEntity(KeywordGroup.class, response.getResponse().getJSONObject("keywords"), this.skipNonExistingFields);
to:
KeywordGroup keywords = new KeywordGroup();
So no keywords in the result but the rest of the answer ist parsed right.

Returning JSON response from Servlet to Javascript/JSP page

I think (actually I KNOW!) I'm doing something wrong here I am trying to populate some values into HashMap and add each hasmap to a list which will be added to a JSON object:
JSONObject json = new JSONObject();
try
{
Map address;
List addresses = new ArrayList();
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new HashMap();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
My problem is I know this is returning a string, which I cannot seem to parse (which is the problem). My question is how do I return the actual JSON encoded string (or even should I be doing this?) or what is the best method of attack for this type of problem. The JavaScript I am using for this is below:
function getReadyStateHandler(req)
{
// Return an anonymous function that listens to the
// XMLHttpRequest instance
return function ()
{
// If the request's status is "complete"
if (req.readyState == 4)
{
// Check that a successful server response was received
if (req.status == 200)
{
msgBox("JSON Response recieved...");
populateDatagrid(req.responseText.toJSON());
}
else
{
// An HTTP problem has occurred
alert("HTTP error: " + req.status);
}
}
}
}
Note the JSON Response comes back fine, but its a string. Any advice is greatly appreciated. I am also opening to using googles Gson, but don't have too much knowledge on that.
Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?
If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

Can anyone help with a java problem regarding record stores?

I have this code. And basically this returns the correct data without the town qualities. When I add the town qualities the method returns nothing, not even the orginal data that it has been and I dont know why. Can anyone see a problem?
protected void listRecords() {
mListForm.deleteAll(); // clear the form
try {
RecordStore rs = RecordStore.openRecordStore("Details", true);
RecordEnumeration re = rs.enumerateRecords(null, new RecordSorter(), false);
while (re.hasNextElement()) {
byte [] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
// extract the name and the age from the record
int endOfName = record.indexOf(";");
int endOfDesc = record.indexOf(";" , endOfName + 1);
int endOfTown = record.indexOf (";", endOfDesc + 1);
String name = record.substring(0, endOfName);
String desc = record.substring(endOfName + 1, endOfDesc);
String town = record.substring(endOfDesc +1, endOfTown);
mListForm.append(name + " aged: "+ desc + " " + town);
}
rs.closeRecordStore();
}
catch(Exception e){
mAlertConfirmDetailsSaved.setString("Couldn't read details");
System.err.println("Error accessing database");
}
mDisplay.setCurrent(mListForm);
}
Have you tried running it in the debugger? Is the exception happening? Are the three semicolons present in the record? Is there a limit on mDisplay's string size? When setCurrent is called, is the mListForm correct?
In other words, what have you done so far and where is it definitely right, and where does it become wrong?

Categories

Resources