JSON Object parsing problem in Android with Volley library - arrays

I am trying to get JSON response from server and then display it in my android but failing to do so due to parsing error
my server response jsonformat= {
"Result": "Login Success",
"User_Name:": "Ayan"
}
But in android I can't ge the second object and it is returned as null
enter image description here

In your response, you have the field like "User_Name:" or did you wrote the response wrong?
JsonObject object = new JsonObject(response);
String result = object.getString("Result");
String userName = object.getString("User_Name:");
check this #Ayan

Related

JSON parsing problem in Android with Volley library

I am trying to get JSON response from server and then display it in my android but failing to do so due to parsing error
Android error
Caused by: org.json.JSONException: Value [{"Result":"Login Success","User_Name:":"Ayan"}] of type org.json.JSONArray cannot be converted to JSONObject
enter image description here
In your response, you have the field like "User_Name:" or did you wrote the response wrong?
check the second field clearly ["User_Name:":"Ayan"]
JsonObject object = new JsonObject(response);
String result = object.getString("Result");
String userName = object.getString("User_Name:");
It should match as like the field else it will give the exception
try this
JSONArray jsonarray = new JSONArray(response);
JsonObject object = jsonarray.getJSONObject(0);
String result = object.getString("Result");
String userName = object.getString("User_Name:");

Unity/Android ServerAuthCode has no idToken on Backend

I have an unity app and use the google-play-games plugin with google *.aar versions 9.4.0. I lately changed my Backend (Google App Engine) from php to java. My problem is the following: in php the serverauthcode is used to get the users data (in JWT format) - it was working fine. So I changed to a Java servlet and I am failing since 2 days to get a valid idtoken. I am able to recieve the server auth code from my app and a valid token response is made by GoogleAuthorizationCodeTokenRequest (see code snippet). Unfortunately it does not contain any idtoken content but a valid auth_token. So I can not get the user id to identifiy the user. When I call tokenResponse.parseIdToken(); it is failing with a NullPointerException.
servlet code (authCode is the serverAuthCode I send from the play-games-plugin inside Unity to my GAE):
// (Receive authCode via HTTPS POST)
// Set path to the Web application client_secret_*.json file you downloaded from the
// Google Developers Console: https://console.developers.google.com/apis/credentials?project=_
// You can also find your Web application client ID and client secret from the
// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
// object.
String CLIENT_SECRET_FILE = "/mypath/client_secret.json";
// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
clientSecrets.getDetails().getTokenUri(),
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode,
REDIRECT_URI) // Specify the same redirect URI that you use with your web
// app. If you don't have a web version of your app, you can
// specify an empty string.
.execute();
String accessToken = tokenResponse.getAccessToken();
// Get profile info from ID token -> HERE IT THROWS AN EXCEPTION.
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
String userId = payload.getSubject(); // Use this value as a key to identify a user.
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
the token response looks like (its invalid now):
{
"access_token" : "ya29.CjA8A7O96w-vX4OCSPm-GMEPGVIEuRTeOxKy_75z6fbYVSXsdi9Ot3NmxlE-j_t-BI",
"expires_in" : 3596,
"token_type" : "Bearer"
}
In my PHP GAE I always had a idToken inside this constuct which contained my encrypted data. But it is missing now?! So I asssume I do somthing differently in Java or I made a mistake creating the new OAuth 2.0 Client on the google console.
I checked the accessToken manually via:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.CjA8A7O96w-vX4OCSPm-GMEPGVIEu-RTeOxKy_75z6fbYVSXsdi9Ot3NmxlE-j_t-BI
{
"issued_to": "48168146---------.apps.googleusercontent.com",
"audience": "48168146---------.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/games_lite",
"expires_in": 879,
"access_type": "offline"
}
Is there something I do not see? Help is very much appreciated...
I found a root cause discussion inside the unity plugin "play-games-services" on github:
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1293
and
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1309
It seems that google switching their authentication flow. In the given links they are talking about adding the email scope inside the plugin to get the idtoken again. I'll try that in the next days and share my experience.
Here is a good explaination about what happens:
http://android-developers.blogspot.de/2016/01/play-games-permissions-are-changing-in.html
If you do what paulsalameh said here (Link to Github) it will work again:
paulsalameh: Sure. After you import the unitypackage, download NativeClient.cs and
PlayGamesClientConfig.cs from my commits (#1295 & #1296), and replace
them in the correct locations.
Afte that "unity play-services-plugin" code update you will be able to add AddOauthScope("email") to PlayGamesClientConfiguration, which allows your server to get the idtoken with the serverAuthCode again...
Code snippet from Unity:
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("email")
.AddOauthScope("profile")
.Build();
Now I am back in business:
{
"access_token" : "ya29.Ci8..7kBR-eBdPw1-P7Pe8QUC7e_Zv7qxCHA",
"expires_in" : 3600,
"id_token" : "eyJhbGciOi......I1NiE0v6kqw",
"refresh_token" : "1/HlSZOo......dQV1y4E",
"token_type" : "Bearer"
}

How to send dictionary with array using JSON?

My fellow co-worker backend programmer said that he has configure an API that expect to receive something like this from my mobile app:
[{"id":50},{"id":60}]
I'm using Alamofire which receive param dictionary to be sent. But I believe this is also the same mechanism using NSURLSession or any other third party plugins.
The question is: how should I construct the dictionary to send an array of ids, like how a HTTP form can have several text field with the same id, and then it will be received on the server end as an array of id? What I've tried so far and all fails:
param.setValue(50, forKey:"id");
param.setValue(60, forKey:"id");
// this only send the last single value
param.setValue([50, 60], forKey:"id");
// this results in error (415 unsupported media type)
param.setValue(50, forKey:"id[0]");
param.setValue(60, forKey:"id[1]");
// this also results in error (415 unsupported media type)
How can I send this correctly just like how web form send? Thanks.
I think keyword for your question is "Alamofire send json"
If your server accepts json data, you can do like this:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = [["id":50],["id":60]]
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
}
Good luck!
The problem with the first method is you're overwriting the value for the key id, that's the reason why it only sends the last value. Try sending the params as an array.
let dict = NSMutableArray()
param.setValue(50, forKey:"id")
dict.addObject(param)
param.setValue(60, forKey:"id")
dict.addObject(param)
Pass the dict as the parameter for the request method.

Trying to retrieve first string from PubNub history Response

I know that the response from the pubnub history() is:
[["message","Message","message"],"Start Time Token", "End Time Token"]
im creating an string to receive the response:
String msg = response.toString();
And this should give me the full array, but now to retrieve the first message im doing this:
String[] msgOne = msg[0];
And this is not working.
for pubnub history method , the response is a org.json.JSONArray so to get the messages array you can use something like this.
JSONArray messages = (JSONArray)( ((JSONArray)response).get(0));
JSONArray class here http://www.json.org/javadoc/ provides more info about the methods that you can use on messages variable.

how can I get more error messages out of solrj SolrException

When I send queries to Solr using solrj, I sometimes get SolrException's thrown. When I dig through the exception, it just says "Bad Request", and gives the HTTP return code (which is 400).
When I take the request URL and put it in my browser, I was able to see a richer error message. The browser displays an error message saying one of the fields names is not valid.
I would like to be able to capture this inside my log file. I was able to capture this by copying all the parameters to an Apache HTTP Client POST request (I'm using POST and not GET because GET made the URL too long) and re-executing the request, but this is inefficient. Is there a way to get error message out of SolrException directly?
Here's what I'm doing:
catch (SolrServerException e) {
if(e.getRootCause() instanceof SolrException) {
SolrException ee = (SolrException) e.getRootCause();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(SOLR_URL);
// copy params over
Iterator<String> iter = request.getParams().getParameterNamesIterator();
while(iter.hasNext()) {
String p = iter.next();
method.setParameter(p, request.getParams().get(p));
}
int statusCode;
try {
// re execute and display the error message
statusCode = client.executeMethod(method);
logger.error(method.getResponseBodyAsString());
} catch (Exception e1) {
// TODO Auto-generated catch block
}
}
These messages aren't available via SolrJ. You can see them in solr's log file, but there is no way to capture them in your client, since solr only returns the 400 error status with a generic message to the client :(

Resources