I am retrieving single rows from an SQL table as a JSONObject. They looks like this but longer:
{"UserId":1111,"FirstName":"null","LastName",:"null","City":"Dallas","State":"Select"}
I want to extract the values and place them in Android TextView fields that correspond to the keys. The null string values should to be replaced with blank space. I was unable to do this with Maps, which were the closest I've gotten to what I want. I enter them in the TextViews like so:
firstname.setText(map.get("FirstName"));
Any established approach to this problem, whether they be lists, arrays, or hashmaps, would be appreciated.
you can import org.json; and use JSONObject for each row
JSONObject reader = new JSONObject(row);
int userId = reader.getIn("UserId");
String firstName = reader.getString("FirstName");
String lastName = reader.getString("LastName");
String city = reader.getString("City");
String state = reader.getString("State");
I suggest you use Gson to map the JSON into a class:
String jsonString = {"UserId":1111,"FirstName":"null","LastName",:"null","City":"Dallas","State":"Select"}
Row row = new Gson().fromJson(jsonString, Row.class);
Where Row.java is:
public class Row{
@SerializedName("UserId")
String userId;
@SerializedName("FirstName")
String firstName;
@SerializedName("LastName")
String lastName;
@SerializedName("City")
String city;
@SerializedName("State")
String state;
}
This is probably too late but it might be helpful to someone, you can do this
JSONObject dbJsonObj = new JSONObject(dbData);
HashMap<String, Object> map = new HashMap<>();
Iterator<String> iter = dbJsonObj.keys();
while (iter.hasNext()) {
String key = iter.next();
map.put(key, dbJsonObj.get(key));
}
and then
String firstName = (String) map.get("FirstName");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.