copy/map json/data class structure in kotlin - json

I am newbie in kotlin and I try to copy a JSON structure to another one in an efficient way.
I have an API called getData() how send back a data structure defined as below:
data class DataA(
var id: String,
var cartItems: List<CartItem>,
}
When the getData sent back the DataA structure, I have to map or translate it to another structure defined as below:
data class DataB(
var cartItems: List<CartItem>,
}
Is there an easy way to do it? I know that kotlin can easily encapsulate calls to make it nice.
Thanks

Since you simply need to convert an instance of DataA to an instance of DataB, what you can do is DataB(dataA.cartItems), where dataA is the instance of DataA.
Note, however, that if for any reason you modify any item of cartItems from dataA, this change will be reflected also to dataB, since they share the same list object.

Related

Is there a way to define a to_json handler in GDScript?

I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.

Call API using Refit and deserialize to dynamic

I'm calling a REST service using Refit and I want to deserialize the JSON that is returned as a dynamic type.
I tried defining the interface as
[Get("/foo")]
Task<dynamic> GetFoo();
but the call times out.
I know I can deserialize to a dynamic like this
var mockString = "{ title: { name: 'fred', book: 'job'} }";
dynamic d = JsonConvert.DeserializeObject(mockString);
but I can't figure out what to pass to Refit to get it to do the same.
Another option would be to get Refit to pass the raw JSON back so I can deserialize it myself but I can't see a way to do that either.
Any ideas?
You can define your interface to return a string and get the raw JSON that way:
[Get("/foo")]
Task<string> GetFoo();
As described here:
https://github.com/paulcbetts/refit#retrieving-the-response
Refit uses JSON.NET under the hood, so any deserialization that works with that will work with Refit, including dynamic. The interface you have described is exactly right.
Here's a real working example:
public interface IHttpBinApi
{
[Get("/ip")]
Task<dynamic> GetIp();
}
var value = await RestService.For<IHttpBinApi>("http://httpbin.org").GetIp();
If you are using iOS and Refit 4+, you might be seeing this bug: https://github.com/paulcbetts/refit/issues/359
As Steven Thewissen has stated, you can use Task<string> as your return type (or Task<HttpResponseMessage>, or even Task<HttpContent>) to receive the raw response and deserialize yourself, but you shouldn't have to -- the whole point of Refit is that it's supposed to save you that hassle.

Decomposing data from a json withangularjs

I have a json file that is requested from a server so i can't modify how is sent, but all the data i need is there, so i want to put that data into the charts, the thing is how i can break down the json file, because the relevant data is nested, the structure is
estados(array of object)
id (property)
name (property)
localidades (array of object)
id (property)
name (property)
type1 (object)
type2 (object) etc..
i need to retrieve the id data from the object estados and localidades then especific data one of the objects nested in localidades.
How i can do that? i only know how to go through every nested object by iteration, but decomposing it?
here is a json sample :
http://www.jsoneditoronline.org/?id=9cd4c3af94f14b1cca2d35226794ea78
The Lodash library (Or Underscore, if you prefer) is what you are looking for. You can use it to manipulate your collections any way you want (pretty much). You could potentially do without helper libraries, but it is much easier (and sometimes faster, though browser dependent [ref]) to do it this way.
Here are some examples in the jsFiddle I put together for a demo. Some example of how to access particular property of an object inside an array of objects:
$scope.findObjects = function () {
var estado = _.find($scope.allJson, {
"idEstado": $scope.idToSearch
});
$scope.exampleOutput = _.filter(estado.localidades, function (item) {
return item.demanda && (item.demanda.ata > 5);
});
};

Manually parse json data according to kendo model

Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model?
Maybe something like kendo.parseData(json, model), which will return array of objects?
I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:
function parse(model, json) {
// I initialize the model with the json data as a quick fix since
// setting the id field doesn't seem to work.
var parsed = new model(json);
var fields = Object.keys(model.fields);
for (var i=0; i<fields.length; i++) {
parsed.set(fields[i], json[fields[i]]);
}
return parsed;
}
Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.
I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.
kendo.data.DataSource.prototype.parse = function (data) {
return this.reader.data(data);
// Note that the original data will be modified. If that is not what you want, change to the following commented line
// return this.reader.data($.extend({}, data));
}
// ...
someGrid.dataSource.parse(myData);
If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.

Cast JSON to Mongoose Schema to call Schema Method

I've looked at this question (Is there a native feature to convert string based JSON into Mongoose Schema object instance?) and it's related to my question but doesn't do exactly what I'm looking for.
Essentially, I have JSON I've fetched from an Express response and I'd like to cast it to a Mongoose object for the purposes of calling a schema method on the object.
My schema looks something like this:
var BlahSchema = new Schema({
folder: String,
filename: String,
original: String
});
...
// This is the function I wish to cal
BlahSchema.virtual('url').get(function () {
...
});
From what I understand, when I have an object matching BlahSchema, I can call the method via a simple object.url.
I have two questions. First, the JSON I'm retrieving these objects from erases their schema, right? I'm retrieving these from the database via Blah.search(...function(err, blahs)). This all gets encoded into a JSON object which I return via callback(req, res, search_result) where search_result is an object created via search_result.blahs = blahs, etc. Is there any way to preserve this schema across calls? This would be the preferred method.
Second, if the above is not possible, how do I re-cast JSON to schema without using the save() function mentioned in the answer to the question I pose above? I don't want to re-add objects to the database; I just want to use a method defined for that schema.
EDIT: Express is pretty sick. All you have to do is blah(object).method_name, where blah = mongoose.model('blah')
I save a User (Schema) object to redis in plain JSON.
Get the userData (string) and parse it to JSON object:
var user = new User(JSON.parse(userData))
... and you have all the methods of your User schema.