I am receiving the data from the api but the code following do not work for some reason
Here is the code:
ListeningExecutorService service = MoreExecutors.listeningDecorator(newFixedThreadPool(50));
final ListenableFuture<JsonElement> userfromapi = mClient.invokeApi("userinfo",null, "GET", null);
Futures.addCallback(userfromapi, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(final JsonElement result) {
final JsonArray contacts = result.getAsJsonArray();
final String jsonString = contacts.getAsJsonObject().get("id").getAsJsonPrimitive().getAsString();
final String facebookid = contacts.getAsJsonObject().getAsJsonPrimitive("id").getAsString();
final String name = contacts.getAsJsonObject().getAsJsonArray("first_name" + "last_name").toString();
final String imgurl = "https://graph.facebook.com/" + facebookid + "/picture";
}
The problem is that, after the success call back getting the individual ids, name, etc
Make model class- For e.g
public class MyClass{
#SerializedName("Name")
private String Name;
public String getName() {
return Name;
}
}
for e.g Fetch data like this -
JSONObject jsonObject = new JSONObject(response);
MyClass myClassModel = new Gson().
fromJson(jsonObject.get("JsonArrayName").toString(),
new TypeToken<MyClass>() {
}.getType());
Related
I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111}
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111}
Now I want to convert the above JSON into my POJO instances that maps to each part of the String. Suppose the POJO is called userList. Then I need to split up the JSON String to 2 userListObjects.
Your Pojo class will look like:
public class userList{
private String countryName;
private String countryCode;
private Long phoneNo;
private Integer campaignId;
//Getters,Setters
}
You can also use this_link to generate pojo just by copying and pasting your json.
Use the following snippet to generate the list.
JsonParser jsonParser = new JsonParser();
String jsonData = "[{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111},{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111}]";
JsonElement parsedJsonElement = jsonParser.parse(jsonData);
if(parsedJsonElement.isJsonArray()){
JsonArray parsedJsonArray = parsedJsonElement.getAsJsonArray();
List<User> userList = new ArrayList<User>();
for(JsonElement jsonElement : parsedJsonArray){
String countryName = "";
String countryCode = "";
long phoneNo = 0;
int campaignId = 0;
Iterator<Entry<String, JsonElement>> iterator = jsonElement.getAsJsonObject().entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> next = iterator.next();
String key = next.getKey();
if(key.equals("countryName")){
countryName = next.getValue().getAsString();
}else if(key.equals("countryCode")){
countryCode = next.getValue().getAsString();
}else if(key.equals("phoneNo")){
phoneNo = next.getValue().getAsLong();
}else if(key.equals("campaignId")){
phoneNo = next.getValue().getAsInt();
}
}
userList.add(new User(countryName, countryCode, phoneNo, campaignId));
}
}
public class User {
String countryName;
String countryCode;
long phoneNo;
int campaignId;
public User(String countryName, String countryCode, long phoneNo, int campaignId) {
super();
this.countryName = countryName;
this.countryCode = countryCode;
this.phoneNo = phoneNo;
this.campaignId = campaignId;
}
}
I have a very basic problem.
I read though the LibGDX documentation a few times regarding JSON and Google around for an answer but it still does't work..
Basically I'm pulling json from a server like such which works as:
{"id":1,"facebook_id":"23432232","json":"{\"json\":\"test\"}"}
I have a class like this:
public class ServerJson
{
public static final String NAME = "ServerJson";
private int id;
private String facebookID;
private String json;
public ServerJson(){}
public ServerJson(int id, String facebookID, String json)
{
this.id = id;
this.facebookID = facebookID;
this.json = json;
}
public int getId() {
return id;
}
public String getFacebookID() {
return facebookID;
}
public String getJson() {
return json;
}
When I try to parse the code, it doesn't work. I get null:
String resultString = httpResponse.getResultAsString(); //{"id":1,"facebook_id":"23432232","json":"{\"json\":\"test\"}"}
Json json = new Json();
ServerJson serverJson = json.fromJson(ServerJson.class, resultString);
log(serverJson.getFacebookID()); //<< Is null.
Make sure the fields of your object class match up with the fields of the json object.
I have several classes like this. I want to convert the classes into JSONObject format.
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("id")
private Integer mId;
#SerializedName("name")
private String mName = "";
#SerializedName("email")
private String mEmail;
public Integer getId() {
return mId;
}
public void setId(Integer id) {
mId = id;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
}
I know that I can convert these classes to JSONObject format as follows:
User user = new User();
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("id", user.getId());
jsonObj.put("name", user.getName());
jsonObj.put("email", user.getEmail());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem is that I need to do this for a lot of different classes that are much longer than this across a lot of files. Can I use GSON to fill the JSONObject from myClass so that I don't need to edit every time the class structure changes?
The following returns a JSON string but I need it as an Object as when I send it to the system that sends the requests via a REST API it sends with unwanted quotation marks.
User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);
When I use this in another JSON builder that asks for an Object I get
{"request":"{"id":"100","name":"Test Name","email":"test#example.com"}"}
When I want
{"request":{"id":"100","name":"Test Name","email":"test#example.com"}}
I found that the following works with GSON:
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is not type safe, however.
Here is a crude example you can use to use Reflection to build the JSONObject..
Warning it's not pretty and does not contain really type-safety.
public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
JSONObject object = new JSONObject();
Class<?> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof SerializedName){
SerializedName myAnnotation = (SerializedName) annotation;
String name = myAnnotation.value();
Object value = field.get(obj);
if(value == null)
value = new String("");
object.put(name, value);
}
}
}
return object;
}
Here is an example usage:
User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));
Output
{
"id": "",
"name": "",
"email": ""
}
Try with this code:
// Returns the JSON in a String
public String getJSON()
{
Gson gson = new Gson();
return gson.toJson(this);
}
// Builds the Model Object from the JSON String
MyModel model =new MyModel();
JSONObject j = new JSONObject(model.getJSON());
I have a JSON string like this:
{
"response":[2,
{
"id":"187",
"name":"John",
"surname":"Corner"
},
{
"id":"254",
"name":"Bob",
"surname":"Marley"
}
]
}
How can I parse it using GSON lib in Java?
I tried:
static class SearchRequest {
private Names[] response;
static class Names {
private int id;
private String name;
private String surname;
}
}
but it doesn't works :(
response array contains not only Names, it also contains an integer value: response[0]=2.
So you must use something like
private Object[] response;
ADD:
I think, you have no need to change your JSON, because your response is private, so you should use getters:
static class SearchRequest {
private Object[] response;
static class Names {
private int id;
private String name;
private String surname;
}
public List<Names> getNames() {
List list = new ArrayList();
list.addAll(Arrays.asList(response));
return (List<Names>) list.subList(1, response.length);
}
public int getAmount() {
return (Integer) response[0];
}
public void setNames(List<Names> names) {
response = new Object[names.size() + 1];
response[0] = names.size();
for (int i = 0, namesSize = names.size(); i < namesSize; i++) {
response[i + 1] = names.get(i);
}
}
}
I prepared a sample code for testing your case, used gson-2.1.jar as library and run it correctly. I modified your JSON string by removing "2," from the beginning of response array since it caused exceptions. Take a look at and test this code:
import com.google.gson.Gson;
public class Test
{
static class SearchRequest
{
private Names [] response;
static class Names
{
private int id;
private String name;
private String surname;
}
}
public static void main ( String [] args )
{
Gson gson = new Gson();
String str = "{ \"response\":"
+ "[{\"id\":\"187\",\"name\":\"John\",\"surname\":\"Corner\"},"
+ "{\"id\":\"254\",\"name\":\"Bob\",\"surname\":\"Marley\"}]}";
SearchRequest request = new SearchRequest();
request = gson.fromJson( str, SearchRequest.class );
System.out.println( "name of 1st: " + request.response [ 0 ].name );
System.out.println( "surname of 2nd: " + request.response [ 1 ].surname );
}
}
Output:
name of 1st: John
surname of 2nd: Marley