I am experimenting with GraphQL on Android using apollo-client and am using GitHub's GraphQL API. I am hitting an API to give me a list of repos owned by a user. Everything works fine but the response that I get is not in JSON format but in String format.
The response looks like this:
Data{user=User{__typename=User,
repositories=Repositories{__typename=RepositoryConnection, nodes=
[Node{__typename=Repository, name=testrepository}]}}
when I try hitting the url through Insomnia (GraphQL rest client) I get the response in JSON format but in my app I get the response in above format. I tried passing content-type : "application/json; charset=utf-8" in header but no success.
Here is how I am fetching the response:
public void fetchRepoList(String userName, String authHeader, final ResponseCallback responseCallback) {
GraphQL.getInstance().getApolloClient(authHeader)
.query(githubRepoList.repoListAPI.FindQuery.builder().repoOwner(userName).build())
.enqueue(new ApolloCall.Callback<githubRepoList.repoListAPI.FindQuery.Data>() {
#Override
public void onResponse(#Nonnull Response<githubRepoList.repoListAPI.FindQuery.Data> response) {
Log.d(TAG, "response" + response)
}
#Override
public void onFailure(#Nonnull final ApolloException exception) {
}
});
}
I want to put the response in a List of Model class and for that I need the response in JSON format. Searched for this issue but didn't got any proper solution.
I am using apollo client 0.3.2
[Edit:1]
I tried making the call to the GitHub GraphQL API with Okhttp and this time I got this response:
{"data":{"__schema":{"queryType":{"name":"Query"},"mutationType":{"name":"Mutation"},"subscriptionType":null,"types":[{"kind":"SCALAR","name":"Boolean","description":"Represents `true` or `false` values.","fields":null,"inputFields":null,"interfaces":null,"enumValues":null,"possibleTypes":null},{"kind":"SCALAR","name":"String","description":"Represents textual data as UTF-8 character sequences. This type is most often used by GraphQL to represent free-form human-readable text.","fields":null,"inputFields":null,"interfaces":null,"enumValues":null,"possibleTypes":null},{"kind":"OBJECT","name":"Query","description":"The query root of GitHub's GraphQL interface.","fields":[{"name":"codeOfConduct","description":"Look up a code of conduct by its key","args":[{"name":"key","description":"The code of conduct's key","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String","ofType":null}},"defaultValue":null}],"type":{"kind":"OBJECT","name":"CodeOfConduct","ofType":null},"isDeprecated":false,"deprecationReason":null},{"name":"codesOfConduct","description":"Look up a code of conduct by its key","args":[],"type":{"kind":"LIST","name":null,"ofType":{"kind":"OBJECT","name":"CodeOfConduct","ofType":null}},"isDeprecated":false,"deprecationReason":null},{"name":"license","description":"Look up an open source license by its key","args":[{"name":"key","description":"The license's downcased SPDX ID","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String","ofType":null}},"defaultValue":null}],"type":{"kind":"OBJECT","name":"License","ofType":null},"isDeprecated":false,"deprecationReason":null},{"name":"licenses","description":"Return a list of known open source licenses","args":[],"type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"LIST","name":null,"ofType":{"kind":"OBJECT","name":"License","ofType":null}}},"isDeprecated":false,"deprecationReason":null},{"name":"marketplaceCategories","description":"Get alphabetically sorted list of Marketplace categories","args":[{"name":"includeCategories","description":"Return only the specified categories.","type":{"kind":"LIST","name":null,"ofType":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String","ofType":null}}},"defaultValue":null},{"name":"excludeEmpty","description":"Exclude categories with no listings.","type":{"kind":"SCALAR","name":"Boolean","ofType":null},"defaultValue":null},{"name":"excludeSubcategories","description":"Returns top level categories only, excluding any subcategories.","type":{"kind":"SCALAR","name":"Boolean","ofType":null},"defaultValue":null}],"type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"LIST","name":null,"ofType":{"kind":"NON_NULL","name":null,"ofType":{"kind":"OBJECT","name":"MarketplaceCategory","ofType":null}}}},"isDeprecated":false,"deprecationReason":null},{"name":"marketplaceCategory","description":"Look up a Marketplace category by its slug.","args":[{"name":"slug","description":"The URL slug of the category.","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String","ofType":null}},"defaultValue":null},{"name":"useTopicAliases","description":"Also check topic aliases for the category slug","type":{"kind":"SCALAR","name":"Boolean","ofType":null},"defaultValue":null}],"type":{"kind":"OBJECT","name":"MarketplaceCategory","ofType":null},"isDeprecated":false,"deprecationReason":null},{"name":"marketplaceListing","description":"Look up a single Marketplace listing","args":[{"name":"slug","description":"Select the listing that matches this slug. It's the short name of the listing used in its URL.","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String","ofType":null}},"defaultValue":null}],"type":{"kind":"OBJECT","name":"MarketplaceListing","ofType":null},"isDeprecated":false,"deprecationReason":null},{"name":"marketplaceListings","description":"Look up Marketplace listings","args":[{"name":"after","description":"Returns the elements in the list that come after the specified cursor.","type"
This response doesn't even have required data about the repositories. It is not even related to the list of repositories.
Therefore, I went back to the old method and made the call using apollo. Now, since apollo creates these model classes from standard GraphQL queries, how do I create a list of this model class.
I went through the apollo sample-app on github and came across this piece of code:
List<FeedEntry> feedResponseToEntriesWithRepositories(Response<FeedQuery.Data> response) {
List<FeedEntry> feedEntriesWithRepos = new ArrayList<>();
final FeedQuery.Data responseData = response.data();
if (responseData == null) {
return Collections.emptyList();
}
final List<FeedEntry> feedEntries = responseData.feedEntries();
if (feedEntries == null) {
return Collections.emptyList();
}
for (FeedEntry entry : feedEntries) {
if (entry.repository() != null) {
feedEntriesWithRepos.add(entry);
}
}
return feedEntriesWithRepos;
}
Here the feedEntries() method returns the list of feeds, this method is in the auto-generated model class file in the apollo directory. I went and checked my model file and there were no methods which returns a list of repos (as in my case). The file is too large to post here but if community want's to have a look at it I can post it here.
By the way, I tried something like this with my code:
List<githubRepoList.repoListAPI.FindQuery.Node> repoList = new ArrayList<>();
final githubRepoList.repoListAPI.FindQuery.Data repoListData = response.data();
final List<githubRepoList.repoListAPI.FindQuery.Node> finalRepoList = repoListData.(which method to call from the auto-generated class file?)
Here, Node is a class in my auto-generated model file in the apollo directory and this class should have a method which returns a list of repo model class.
I know I am doing something wrong here. I think there is some other way to create of list of these model classes.
the response is not in JSON format
The response was in JSON format. It is now in the form of a githubRepoList.repoListAPI.FindQuery.Data object. That class was code-generated for you based on your GraphQL document. Quoting the Apollo-Android documentation, with emphasis added:
Apollo-Android is a GraphQL compliant client that generates Java models from standard GraphQL queries
In particular, Apollo-Android generates toString() implementations on those Java model classes. In your case:
Data holds a User in a user field
User holds a RepositoriesConnection, renamed to Repositories, in a repositories field
The repositories collection holds a single Repository
The reason for using Apollo-Android is so that you do not have to deal with the JSON yourself. If, instead, you want to parse JSON yourself, get rid of Apollo-Android and just use OkHttp to make the Web service calls.
In my app, I get and parse a JSON stream from a wordpress (RESP API v2) website.
I use, OKHTTP, RETROFIT with GSON converter to read and parse the stream into my objects.
Usually, my GSON converter expect an object but, because of a recent update, the website gives me a boolean (false). The value isn't set yet.
This is my question: "Can I handle different type of values for the same variable name with GSON Serialize and how?"
Thank you!
This is my object:
public static class StageProfileImage {
//////////////////////////////////////////////////
// Variables
//////////////////////////////////////////////////
#SerializedName("url")
private String stageProfileImageUri;
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// Setters & Getters
//////////////////////////////////////////////////
public String getStageProfileImageUri() {
return stageProfileImageUri;
}
public void setStageProfilUri(String stageProfileImageUri) {
this.stageProfileImageUri = stageProfileImageUri;
}
/////////////////////////////////////////////
}
Important: I can't modify the stream.
try #SerializedName(value = "url", alternate = {"altkey1", "altkey2"})
Edit: Changed to a more generic example.
Thanks but it isn't my problem. In fact, GSON can't convert the stream from the website because instead of this:
"stage_profile_image" : {
...
}
My stream give me that:
"stage_profile_image" : false
In the first one, I get an object but in the second one I get a boolean which is not the type of value it expects and GSON is unable to do the convertion.
I am trying to figure out how to parse data that comes from Zoho CRM API inside of Android Studio. I am relatively new, but I do know how to parse data from a JSON response like this:
{
"Data": [
{ "subdata": "data"
}
]
}
Something kind of like that I can parse no problem in Android Studio, even with multiple subdata points, it's not that hard. But, I am at a complete loss when it comes to parsing data that looks like this:
{"response":{"result":{"Contacts":{"row":[{"no":"1","FL":
[{"content":"1822766000000272057","val":"CONTACTID"},
{"content":"Lisa","val":"First Name"}]},{"no":"2","FL":
[{"content":"1822766000000119148","val":"CONTACTID"},
{"content":"Eric","val":"First
Name"}]}]}},"uri":"/crm/private/json/Contacts/searchRecords"}}
Does anyone know how to parse data like this inside of Android Studio?
Update: I have a photo of what the JSON looks like in Json Viewer:
Just take it layer by layer. It can get a little verbose so I like to have a class called JSONUtils or something and use convenience methods like this to help parsing JSON without having to wrap everything in try-catch blocks:
/**
* Retrieves a json object from the passed in json object.
* #param json The json object from which the returned json object will be retrieved.
* #param key The key whose value is the json object to be returned.
* #return A json object.
* */
public static JSONObject jsonObjectFromJSONForKey(JSONObject json, String key) {
try {
return json.getJSONObject(key);
}
catch (JSONException e) {
return null;
}
}
You can make variations of this for any other data types, and by doing so you can just have your try-catch blocks in one area, and just check for null when invoking these kind of methods.
JSONObject responseJSON = JSONUtils.jsonObjectFromJSONForKey(json, "response");
if (responseJSON != null) {
JSONObject resultJSON = JSONUtils.jsonObjectFromJSONForKey(responseJSON, "result");
// So on and so forth...
}
I am sagar, i am trying to implement the Parse Push-Notification in android using REST API (Service), and i am almost got success in implement the Push-Notification in Xamarin-Android using REST API. But i got stuck with one part in sending the Data into REST service. I trying to pass the ParseObject in service, but the in parse table there is a need of Object,(). I have tried to pass the ParseObject as below:
JsonConvert.SerializeObject(ParseUser.CurrentUser)
It convert ParseObject into array and array is not accepted in table and ,i got failed to save it in table. because there i a need of object.
I need solution or suggestion from developer guys. Yours help will be appreciated. I am trying the below code to achieve the result.
public static void RegisterPush(string regristrationId)
{
if (regristrationId != null) {
string appID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string restID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string masterID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
var client = new RestClient ("https://api.parse.com");
var request = new RestRequest ("1/installations", RestSharp.Method.POST);
request.AddHeader ("Accept", "application/json");
request.AddHeader ("X-Parse-Application-Id", appID);
request.AddHeader ("X-Parse-REST-API-Key", restID);
request.Credentials = new NetworkCredential (appID, masterID);
request.Parameters.Clear ();
Console.Error.WriteLine ("ParseUser.CurrentUser-->"+ (ParseObject) ParseUser.CurrentUser);
//JsonConvert.SerializeObject(ParseUser.CurrentUser)
string strJSONContent = "{\"user\" :"+ JsonConvert.SerializeObject(ParseUser.CurrentUser)+",\"owner\":\"" + ParseUser.CurrentUser.ObjectId + "\",\"deviceType\":\"android\",\"GCMSenderId\":\"1234567890\",\"appName\":\"abcdefgh\",\"pushType\":\"gcm\",\"deviceToken\":\"" + regristrationId + "\"}";
Console.Error.WriteLine("json string-->"+ strJSONContent);
request.AddParameter ("application/json", strJSONContent, ParameterType.RequestBody);
client.ExecuteAsync (request, response => {
Console.Error.WriteLine ("response for android parse installation-->" + response.Content);
});
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
}
}`
Output:{"user" :[{"Key":"dealOffered","Value":4},{"Key":"dealRequested","Value":5},{"Key":"displayName","Value":"Cook"},{"Key":"email","Value":"lorenzo#gmail.com"},{"Key":"firstName","Value":"Lorenzo"},{"Key":"lastName","Value":"Cook"},{"Key":"mobileNumber","Value":9999999999.0},{"Key":"picture","Value":{"IsDirty":false,"Name":"tfss-afd25c29-6679-4843-842c-fe01f7fcf976-profile.jpg","MimeType":"image/jpeg","Url":"http://files.parsetfss.com/profile.jpg"}},{"Key":"provider","Value":"password"},{"Key":"userType","Value":"Merchant"},{"Key":"username","Value":"merchant#sailfish.com"},{"Key":"zipCode","Value":2342343}],"owner":"3cF1vHUXkW","deviceType":"android","GCMSenderId":"1234567890123","appName":"Sailfish","pushType":"gcm","deviceToken":"APA91bE3bsTIInQcoloOBE4kdLVVHVTRVtNyA1A788hYSC15wAVu8mUg-lwk7ZPk370rngrK7J6OoLmiM9HRr1CGPaBo6LCNrSUL7erBku4vepaFFkQzgqS6BcAemp"}
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
maven
I found the solution in , parse xamarin docs, in one query , the way is simple, but i little bit hard to found out.
The issue is with the data passing in json format in REST, to pass any pointer using REST API, use as below.
The solution is as below:
`{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"qYvzFzGAzc"
},
"owner":"qYvzFzGAzc",
"deviceType":"android",
"GCMSenderId":"123456789",
"appName":"NiceApp",
"pushType":"gcm",
"deviceToken":"APA91bFeM10jdrCS6fHqGGSkON17UjEJEfvJEmGpRM-d6hq3hQgDxKHbyrqAIxMnEGgbLEZf0E9AllHxiQQQCdEFiNMF1_A8q0n9tGpBE5NKhvS2ZGJ9PZ7585puWqz_1Z1EjSjOvgZ1LQo708DeL2KzA7EFJmdPAA"
}`
It looks like your column user is set up wrong. It should show as a Pointer<_User> not Pointer
If you load this class in your Data Browser, is the "user" key defined as a string, or a Pointer <_User>
This error seems to indicate that this is a string column, which is why the Parse.User object is not being accepted as a valid value. You might have tried setting a string on this key before, which in turn type-locked the "user" key as a string column.
Found it on the examples given on this page - https://www.parse.com/docs/rest
Have you check your REST API connection while passing ParseObject?
Because your error says:
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
Here "code":111This error code comes when server refuse for connection
I am new to android developing, my website returns posts with following format in json:
post= {
'artist':'xxxx',
'title':'xxxx',
'text':'xxxx',
'url':'http://xxxx'
}
I know something about receiving a file from the net and saving it to a SD card, but I want to do it on fly, parse it and show in on some text view, can you please give me some simple code for this?
I tried searching but I can't find a good tutorial for this, so this is the last place I'm coming to solve my problem.
A good framework for parsing XML is Google's GSON.
Basically you could deserialize your XML as follows (import statements left out):
public class Post {
private String artist, title, text, url;
public Post() {} // No args constructor.
}
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = readFromNetwork(); // Read JSON from network...
Post post = gson.fromJson(jsonString, Post.class);
// Use post instance populated with your JSON data.
}
}
Read more in GSON's user guide.