How to parse nested JSON Using Android? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to parse URL to get JSON response and particular values from that response. I dont have a sample code. Please give me a simple solution.
Below I have posted my URL and Response. I want to GET "School", Name" and Result values.
http://sample.com/login/username/ <username> /password <password>?
{
"response":{
"School":"SBOA",
"Name":"Anitha",
"Class":"Tenth",
},
"Result":"Good",
}
My Code :
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="URL";
String data = "";
System.out.println(strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("response");
System.out.println(jsonRootObject);
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
// int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("School").toString();
// float salary = Float.parseFloat(jsonObject.optString("salary").toString());
// data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";*/
}
//output.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}

To read exactly that JSON, use this:
/** Verify that your strJson string contains this:
* {
* "response":{
* "School":"SBOA",
* "Name":"Anitha",
* "Class":"Tenth",
* },
* "Result":"Good",
* }
*/
String strJson = ??;
Log.d("TAG", "strJson: " + strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONObject response = jsonRootObject.getJsonObject("response");
String schoolString = response.getString("School");
String nameString = response.getString("Name");
String classString = response.getString("Class");
String result = jsonRootObject.getString("Result");
} catch(JSONException e) {
Log.e("TAG", "Error reading json: " + jsonRootObject.toString());
}

If you have a JSONObject named json then follow this for getting school value
try{
jsonRootObject .getJSONObject("response").getString("School");
}catch(JSONException e)
{
e.printStackTrace();
}

Related

Get ID of the room from Json

I need to get the ID of room by its name from JSONObject.
I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json
So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").
Any ideas how to do that?
So far I have something like this:
private static String GetIdRoom(String room) {
String id = "";
JSONObject myResponse = SendHTTP("/groups", "GET", "");
try {
// some code to get ID of room
} catch (Exception ex) {
System.out.println("error - " + ex);
}
return null ;
}
Iterator<?> ids = myResponse.keys();
while( ids.hasNext() ) {
id = (String) ids.next();
if(myResponse.getJSONObject(id).getString("name").equals(room)){
return id;
}
}

How can I make if-else work properly in my try-catch statement?

I have a json array of all names and contacts on my phone, looks something like this:
[{"name":"andy","phone_number":"+123"},{"name":"bob","phone_number":"+456"},{"name":"chris","phone_number":"+789"}]
I check the phone numbers against phone numbers in a db, if there's a match I want to show the name in the recycler view, if no match, then show just the number.
For example, +123, yes, it is in the db, so show andy in the cell in recyclerview. +789 is not in the db, so show +789 in the cell.
Here's what I'm working with so far: it works when there is a match, the if part, but I don't know how to deal with the else part (for when there is no match). If I uncomment my else code it always jumps straight to there.
public void onResponse(String response) {
try {
//name our JSONObject User_Private_Public_Obj, which is response from server
//the response from server will be like:
//{"private_review_ids":[{"reviewid":7,"username":"+123"},{"reviewid":14,"username":"+456"}]}
JSONObject User_Private_Public_Obj = new JSONObject(response);
//Now break up the response from server
//We want the JSON Array part, "private_review_ids"
JSONArray private_ids = User_Private_Public_Obj.getJSONArray("private_review_ids");
for
//get the number of objects in User_Private_Public_Obj
(int i = 0; i < private_ids.length(); i++)
{
//for each object in the array private_ids, name it obj
//each obj will consist of reviewid and username
JSONObject obj = private_ids.getJSONObject(i);
Review review = new Review();
//get the string from sharedpreferences, AllPhonesandNamesofContacts,
//it will be like [{"phone_number":"+123","name":"andy"}, etc...]
//we want this so we can display phone name in recyclerView, if it's a contact
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("AllPhonesandNamesofContacts", "0");
//convert the string above into a json array
JSONArray jsonArray = new JSONArray(json_array);
//set a string to the phone number from the DB,
//the phone number of the person who made the review
phoneNoInDB = obj.getString("username");
//set the setter to the phone number string, the string is
//the phone number of the person who made the review
review.setPhoneNumberofUserFromDB(phoneNoInDB);
//jsonArray is our All Phones and Names of Contacts array
int matching = jsonArray.length();
for (int n = 0; n < matching; n++) {
try {
//for every object in "All Phones and Names of Contacts" array...
JSONObject object = jsonArray.getJSONObject(n);
//if the review maker is a contact...that is,
//if the phone_number in AllPhonesandNamesofContacts equals
//the phone number in the DB
if (object.getString("phone_number").equals(phoneNoInDB)) {
//just for testing purposes...
Toast.makeText(NewActivity.this, object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
//then rip out the other part of the object, the name in
// AllPhonesandNamesofContacts
//of the person who made the review
review.setphoneNameonPhone(object.getString("name"));
//add the review to the sharedReviewList
reviewList.add(review);
}
/* else {
//just for testing...
Toast.makeText(NewActivity.this, " should be green" + object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
review.setphoneNameonPhone(object.getString("phone_number"));
//add the review to the sharedReviewList
//reviewList.add(review);
}*/
} catch (JSONException e) {
System.out.println("error in if else");
//Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//set the adapter to show the random reviews
recyclerView.setAdapter(uAdapter);

getJSONObject and subsequent getString returns null

This is a very straightforward question, but this error is very mysterious to me as I have not been able to find a solution or anyone else who has had this problem. I've also used a very similar technique in another activity and it worked just fine. I am making an android application which makes a POST request to a server. The response is a JSONObject that must be parsed into a number and another JSONObject which must also be parsed, and its values assigned to an array of CurrentGame objects. The first call to getJSONObject works fine, but calling getString on that JSONObject returns the following error:
java.lang.NullPointerException: Attempt to write to field 'java.lang.String com.xxxxx.xxxxx.CurrentGame.oppEmail' on a null object reference
Here is my java code:
private void handleResponse(JSONObject response){
int numGroups = 0;
try{
numGroups = response.getInt("Number");
}catch(JSONException e){
e.printStackTrace();
}
Log.i("Number of Groups", String.valueOf(numGroups));
CurrentGame[] currentGames = new CurrentGame[numGroups];
JSONObject current;
int yourTurn = 0;
for(int i = 0; i < numGroups; i++){
try{
current = response.getJSONObject(String.valueOf(i));
Log.i("Current JSONObject: ", String.valueOf(current));
if(current.has("OppEmail")){
currentGames[i].oppEmail = current.getString("OppEmail");
}
if(current.has("OppName")) {
currentGames[i].oppName = current.getString("OppName");
}
if(current.has("Group")) {
currentGames[i].group = current.getString("Group");
}
if(current.has("YourTurn")) {
yourTurn = current.getInt("YourTurn");
}
if(yourTurn == 0){
currentGames[i].yourTurn = true;
}
else{
currentGames[i].yourTurn = false;
}
}
catch (JSONException e){
e.printStackTrace();
}
}
}
Shouldn't the JSONObject.has() check at least be preventing this error?
I know the first getInt() and getJSONObject are working. Heres the Log:
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx D/Response:﹕ {"Number":2,"0":{"Group":"Test Group 1","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0},"1":{"Group":"Test Group 2","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":1}}
06-21 21:58:56.644 20116-20116/com.xxxxxx.xxxxxt I/Number of Groups﹕ 2
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx I/Current JSONObject﹕ {"Group":"Test Group 1","OppEmail":"xxxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0}
Here's the server code:
$games['Number'] = $numgames;
if($numgames > 0){
$i = 0;
while($row = mysqli_fetch_array($getgames)){
$currGame['Group'] = $row['GroupName'];
// Get the opponent's email and username
if($row['Player1'] != $email){
$opponent = $row['Player1'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
else if($row['Player2'] != $email){
$opponent = $row['Player2'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
// Determine if it is this player's turn
if($row['CurrentPlayer'] != $email){
$currGame['YourTurn'] = 0;
}
else{
$currGame['YourTurn'] = 1;
}
$games[$i] = $currGame;
$i++;
}
}
//Echo array of groups
header('Content-Type: application/json');
$response = json_encode($games);
echo $response;
Thank you in advance for any ideas as to what I'm doing wrong here. I know similar questions have been asked about getString() returning null, but having read them all I'm still very stumped.
Problem is caused by :
currentGames[i].oppEmail = current.getString("OppEmail");
line.
Because currentGames Array is initialized with size 2 but not added any item of type CurrentGame.
Instead of using currentGames[i].oppEmail create a object of CurrentGame class add all values then add it in currentGames Array like:
CurrentGame objCurrentGame=new CurrentGame();
if(current.has("OppEmail")){
objCurrentGame.oppEmail = current.getString("OppEmail");
}
... same for other fields
...
//Add objCurrentGame to Array
currentGames[i]=objCurrentGame;
Parsing json this way is not robust and error prone, it is recommended to use such libraries as
Gson
Jackson
Retrofit
as these open source libraries offer stable implementation for such purposes and there is no need to reinvent the wheel yourself.
example:
YourPojoClass obj = new Gson().fromJson("{SomeJsonString}", YourPojoClass.class);
In this way, you get the strongly typed pojo instance.You don't even need write the POJO class yourself, and there are many online service that can generate the POJO class out of json strings:
http://www.jsonschema2pojo.org/
http://pojo.sodhanalibrary.com/

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]);

java.lang.NullPointerException when trying to parse XML

This problem really has me scratching my head.
I have a chat application that parses xml from the server. It is successful parsing the message text, msg id, but I am getting a nullpointerException for the UserID but I am pulling it from the same location. Please help
// Get messages
NodeList messageList = documentElement.getElementsByTagName("MESSAGE");
ret.messages = new ChatStruct[messageList.getLength()];
Log.v("response","Message Length " + messageList.getLength());
for (int i = 0; i < messageList.getLength(); i++) {
Element messageNode = (Element) messageList.item(i);
ret.messages[i] = new ChatStruct();
// Get messageId
try {
Element messageIdNode = (Element) messageNode.getElementsByTagName("ID").item(0);
String messageId = messageIdNode.getFirstChild().getNodeValue();
System.out.println("messageId = " + messageId);
ret.messages[i].id = Long.parseLong(messageId);
//Log.v("Util","Message ID " + Long.parseLong(messageId));
} catch (Exception e) {
ret.messages[i].id = 0l;
// e.printStackTrace();
}
// Get text
try {
Element textNode = (Element) messageNode.getElementsByTagName("TEXT").item(0);
String text = textNode.getFirstChild().getNodeValue();
System.out.println("text = " + text);
ret.messages[i].textMessage = text.trim();
//Log.v("Util","Message text " + text.trim());
} catch (Exception e) {
ret.messages[i].textMessage = "";
// e.printStackTrace();
}
// Get userId
try {
//ret.messages[i].userId = 1;
//Log.v("Util # userID node","userID should be 1");
Element userIdNode = (Element) messageNode.getElementsByTagName("USERID").item(0);
Log.i("Util # userID node","userIdNode set");
String userId = userIdNode.getFirstChild().getNodeValue();
//String userId = "1";
Log.i("Util # userID node","userId String set");
System.out.println("userId = " + userId);
ret.messages[i].userId = Long.parseLong(userId);
//ret.messages[i].userId = 1;
} catch (Exception e) {
Log.v("Util # userID node", "there was an error " + e);
ret.messages[i].userId = 0l;
// e.printStackTrace();
}
I can hard code the string and it works but other than that the error occurs at
String userId = userIdNode.getFirstChild().getNodeValue();
It makes it up to commented line of code confirming the userIDNode is set
I can't figure out why userID is not coming in from the server here is the XML:
<MESSAGE>
<ID><?php echo $row_shouts['msgid']; ?></ID>
<USERID><?php echo $row_shouts['userid']; ?></USERID>
<GENDER><?php echo $row_shouts['gender']; ?></GENDER>
<ONLINE><?php echo $row_shouts['account_status'];?></ONLINE>
<TDATE><?php echo datee("h:i:s M, d Y", strtotime($row_shouts['date'])); ?></TDATE>
<ICONID><?php echo $iconid; ?></ICONID>
<PIC><?php echo $PIC; ?></PIC>
<MSGPIC><?php echo $row_shouts['media']; ?></MSGPIC>
<PICDATE><?php echo strtotime($row_shouts['picdate']); ?></PICDATE>
<ALIAS><![CDATA[<?php echo $row_shouts['nickname'];?>]]></ALIAS>
<TEXT><![CDATA[<?php echo $mesg;?>]]></TEXT>
</MESSAGE>
Did you check with the DTD file for the supplied Xml, May be USERID is not clearly defined there.
[please share the error logs]
What's the execption say if you print the stack trace? It might be because the user id isn't a long and you're trying to parse it. I don't see any errors in the retrieval of the user id.

Categories

Resources