What type is it in Kotlin? - android

when i covert the API response to object, the data would be wrong. I have no idea.
My API response is Any type.Every data is correct without number data.
for example
D/OKHttp:
result":[
0,
{"memory": {
"distribution":"OpenWrt"
"total":1037029376,
"shared":253952,
"free":946176000,
"cached":27062272,
"available":933396480,
"buffered":2101248
},
{
...
}
}
]
when i Covert to Any type
D/InfoAdapter: result":[0,{"memory":{"distribution":"OpenWrt", total=1.037029376E9, shared=253952.0, free=9.46176E8, cached=2.7062272E7, available=9.3339648E8, buffered=2101248.0},...}]
The number data(1.037029376E9) look like a type, But i have no idea what type is it. Any i don't know how to covert these to Int.
Is anyone can handle this?

Related

gson parse object when there is data and array when no data

I use retrofit2 + gson.
My question is about when server has data it send me json like:
{
"next":false,
"total":4,
"start":0,
"rows":[
{
"calls":29,
"new_calls":29,
"new_quality_calls":10,
"item":"MzY4NzA3NDA0Mw",
"sessions":3,
"calls_per":966.66666666666663
},
{
"calls":15,
"new_calls":15,
"new_quality_calls":5,
"item":"test312312312",
"sessions":2,
"calls_per":750
},
{
"calls":0,
"new_calls":0,
"new_quality_calls":0,
"item":"test",
"sessions":4,
"calls_per":0
},
{
"calls":0,
"new_calls":0,
"new_quality_calls":0,
"item":"test2",
"sessions":2,
"calls_per":0
}
],
"summary":{
"sessions":11,
"calls":44,
"new_calls":44,
"new_quality_calls":15,
"calls_per":400
}
}
But when there is no data, it send me:
{"next":false,"total":0,"start":0,"rows":[],"summary":[]}
The problem is that summary is an object or array is some case.
i use this site to make gson calsses http://www.jsonschema2pojo.org/
When i got data its ok, but when there is no data i got an error:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 56 path
How to solve it automatically by retroft2 (.addConverterFactory(GsonConverterFactory.create())) without manual data parsing?
Add your own converter which will parse AST (readTree), check $.summary type, fix it, and then give this fixed AST to TypeAdapter.

How to parse JSON in Android Studio

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...
}

About how to pass the ParseObject(Object) using Rest API(service) in Installation class in android?

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

How to build JSON Request Body?

I'm trying to build the following JSON Request Body.
It's my first time with JSON and I'm following this examples, but still struggling.
I've been taking a look to GSON but wanted to manage pure JSON first, and maybe for something so small it's not worth it to add GSON library?
Could you help me with the code?
Thanks.
{
locations:
[
{
latLng:
{
lat: 40.900799,
lng: 8.606102
}
},
{
latLng:
{
lat: 42.900799,
lng: 9.606102
}
}
]
}
EDIT:
Here is the Web Service I am trying to consume and here a request sample.
Use json objects.
Do something like that.
Don't write json by hand, you could easily do a mistake.
public JSON() throws JSONException
{
JSONArray locArr=new JSONArray();
locArr.put(createLatLng(40.900799, 8.606102));
locArr.put(createLatLng(42.900799, 9.606102));
JSONObject main=new JSONObject();
main.put("locations", locArr);
Log.d("JSON",main.toString());
}
public JSONObject createLatLng(double lat, double lng) throws JSONException
{
JSONObject latLng=new JSONObject();
latLng.put("lat",lat);
latLng.put("lon",lng);
JSONObject latLngWrap=new JSONObject();
latLngWrap.put("latLng",latLng);
return latLngWrap;
}
JSON notation requires the "" around field names. Values should only be wrapped, if they are string.
{
"locations":
[
{
"latLng":
{
"lat": 40.900799,
"lng": 8.606102
}
},
{
"latLng":
{
"lat": 42.900799,
"lng": 9.606102
}
}
]
}
You can always verify, if you JSON is correct using
http://jsonlint.com/
Expanding on maciekczwa's answer. JSON (unlike arguably XML) isn't really meant to be looked at with human eyes. It very quickly becomes very hard to see where one object starts and ends and what's wrapping what. Use his example to create your main JSON object and then fill it with whatever objects you need to. When you're all done you can convert it to string for transport very easily, without having to look at it, and doing it this way means not having to worry about what labels need to be wrapped in what kinds of quotes etc.
And eskalera is 100% correct. JSON requires all fields to be wrapped in quotes (the rules around whether or not they can be single quotes or *MUST be double quotes vary from implementation to implementation, but again, this is only relevant if you're constructing the JSON manually, as you should only do in instances where it's EXTREMELY simple (and even then... probably not).

Using JSON to create an object in Groovy/Grails

I have a Groovy/Grails website that is being used to send data to Android clients via JSON. I have created both the Android client and the Groovy/Grails website; and they can output the same objects in JSON.
I can successfully create the respective objects in Android by mapping the JSON output to Java objects, however I was wondering if it's possible to use the JSON output to create a new domain object in Groovy/Grails? Is there a way of passing the JSON output to a controller action so that object will be created?
Here is an example of the JSON that I'd like to send;
{
"class":"org.icc.callrz.BusinessCard.BusinessCard",
"id":1,
"businessCardDesigns":[],
"emailAddrs":[
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":1,
"address":"chris#krslynx.com",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":0,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"H"
}
},
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":2,
"address":"cb#i-cc.cc",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":1,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"W"
}
}
]
}
The "class" matches to the Domain I'd like to save to, the ID is the ID of the Domain, then each item within the businessCardDesigns and emailAddrs needs to be saved using similar methods (in the Domain the businessCardDesigns and emailAddrs are ArrayLists). Many thanks in advance!
SOLUTION:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody String json) {
Owner.fromJsonToOwner(json).persist();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
Using the built-in Grails JSON converter makes this easier than the other answers, in my opinion:
import grails.converters.JSON
class PersonController {
def save = {
def person = new Person(JSON.parse(params.person))
person.save(flush:true)
}
}
The other benefits are:
There's no need to muck around in any config files
The resulting JSON object can be manipulated, if necessary, before assigning properties
It's far clearer in the code what's happening (we're parsing a JSON object and setting the properties on the Person entity)
I know you already accepted an answer but if I'm reading your question right, there's a built in "Grails" way to do this.
Create an entry for your action in URLMappings.groovy and turn on request parsing. For example, I create RESTful mappings like so:
"/api/bizCard/save"(controller: "businessCard", parseRequest: true) {
action = [POST: "save"]
}
And then in you controller
def save = {
def businessCardInstance = new BusinessCard(params.businessCard)
....
businessCardInstance.save(flush:true)
}
this might work for you
http://static.springsource.org/spring-roo/reference/html/base-json.html

Categories

Resources