On Continuation to following SO Question/Answer :-
How to get JSON serialized string using Dart Serialization
I want to serialize complex object values in JSON, how can I achieve that using:-
Map toJson() { }
My class heirarchy is :-
class Container {
Containerthis.DPC_ID);
String get Id => DPC_ID;
String get LSDetailUrl => "http://www.indiavotes.com/pc/detail/$DPC_ID/$DB_STATEID/15";
List<GoogleMaps.LatLng> Coordinates;
List<LSElectionResult> ElectionData;
var DPC_ID;
// how to extend following method to serialize complex inner objects too?
Map toJson() {
return {"id": DPC_ID, "ElecData2009": ElectionData};
}
}
class LSElectionResult {
String get WinnerName => DWIN_NM;
String get WinnerParty => DWIN_PRT;
}
Here the first collection - GoogleMaps.LatLng is external class, but I want to serialize it too. But second collection member ElectionData is of my own class LSElectionResult, If I write Map toJson() implementation for LSElectionResult, will it be called automatically if I call Container.toJson() ?
I am going to compile this to JS.
Related
I am calling a rest API from angular, the rest api returns data in JSON Array of Objects like this
Now I am trying to convert it to my model class array but don't getting anywhere can you please guide me.
My Model Class
My Service File
Here it gives error on map and I don't know how to convert it to my model class array to display it in table
Resolved It.
As i was directly getting the array of objects in response, I don't need to convert it and use an interface. So here is my correct code
fetchAllGamesRecord() : Observable<Fifa[]>{
const fifaUrl = `${this.baseUrl}/fetchAllGamesRecord`;
return this.httpClient.get<Fifa[]>(fifaUrl);
}
This function is called like this
this.fifaService.fetchAllGamesRecord().subscribe(
data => {
this.allGameRecord = data;
console.log(`Data = `+data);
}
);
you can do that while calling fetchAllGamesRecord
fetchAllGamesRecord().subscribe( (response: Fifa[]) => {
// do something
}
where Fifa is interface not class
In the Spring framework also Fifa[] doesn't work in REST calls, we need to put it in another class as I showed below, I assume this will work.
export class FifaWrapper {
wrapper: Fifa[];
}
and also use this class in Observable
fetchAllGamesRecord(): Observable<FifaWrapper> {
... do you handling here
}
With dart / flutter it is possible to instantiate an Dart object from a jSON object.
For example, you define the dart class and instantiate an object of that class with the content from a jSON string via the API query.
The question is:
Is there any way that the jSON object contains additional variables that are then also available in the instantiated dart object? The goal is an ultra dynamic App, which is only supplied by the backend.
So far, I've been working with 'fixed' variable names or lists of subobjects.
This approach works perfectly smoothly.
I have not tried the approach of a dynamic variable from a jSON string yet.
I would like to ask if this is possible in principle before I design a concept based on this approach.
{
"widgetType": "radioGroup",
"label": "Level",
"integerValueNew": 200
}
#JsonSerializable()
class Input {
Input();
#JsonKey(required: true) String widgetType;
String label;
factory Input.fromJson(Map<String,dynamic> json) => _$InputFromJson(json);
Map<String, dynamic> toJson() => _$InputToJson(this);
}
In the Dart class only the variables 'widgetType' and 'label' are defined. Also the type of the variable is known, when an objekt is instantiated.
Can a dart object be instantiated from the shown jSON object, which then also contains the integer 'integerValueNew'?
If that works, you can develop a concept for it.
If not, I would work with sub-objects and well-defined variable names in Dart classes. Then the concept has to be broken down to a simple key value mapping.
I also do not know how the dart object should know which type of variable it is at all.
I am trying to parse a JSON response I am receiving from an 3rd party API.
The response returns a json object with N child objects.
The children all conform to the same model/class, but the amount of children can change.
Had it been an array of objects, it would have been trivial, but I am not sure how to do it with an object holding N objects.
I believe I need a custom typeadapter but I can't seem to get it done.
Here is the JSON:
"api":{
"results": 94
"leagues": {
"1":{
"league_id":"1"
"name":"2018 Russia World Cup"
"country":"World"
"season":"2018"
"season_start":"2018-06-14"
}
"2":{...}
"3":{...}
"4":{...}
...
"N":{...}
}
}
So basically it is the "leagues" object I am trying to parse.
I am hoping to end up with a List<League>
For instance, the the root object could have this model:
class Api {
val results: Int
val leagues: List<League>
}
Personally I'd go for a Map<String, League> (assuming the entries in the map would be of class League) for the type of leagues.
class Api {
val results: Int
val leagues: Map<String, League>
}
I think the things to consider here are mostly regarding the order I suppose. If you need to maintain the order of the entries, I'm not sure if Moshi does it automatically or if you need to use a specific implementation of Map to guarantee this.
You can get make the league list in a custom adapter.
data class Api(val results: Int, val leagues: List<League>)
object LeagueListAdapter {
#FromJson fun fromJson(reader: JsonReader, leagueAdapter: JsonAdapter<League>): List<League> {
reader.beginObject()
val result = mutableListOf<League>()
while (reader.hasNext()) {
reader.skipName()
result += leagueAdapter.fromJson(reader)!!
}
reader.endObject()
return result
}
}
Don't forget to add the adapter when building your Moshi instance (Moshi.Builder.add).
I have a class of type A.
This class has several properties, let's call them prop1, prop2 and prop3.
When I'm calling an API, that returns a JSON string representing the object, some properties might be omitted if they are null. Further down the road, however, this object is used to construct a form dynamically (using Formik, but that's unrelated).
This framework expects all properties to be there, and some will be visible dynamically depending on other properties.
So my question, how can I parse a JSON response to my custom class, keeping default values in case properties are omitted in the API response?
What I've tried was:
static getCustomer(id) {
return fetch(process.env.MD_API_URL + 'customers/' + id, { mode: 'cors' })
.then(response => {
let cust = new Customer();
return response.json().then(x => cust = JSON.parse(x));
}).catch(error => {
return error;
});
}
But this returns undefined. Must be doing something wrong...
since typescript is not actually compiled but translated into javascript so all the javascript rules apply.
Therefore deserializing json wont actually create a new instance of the class in question but gives you an object you can "call" Customer during design time.
you could however create an object and then assign the json values like this:
export class Customer {
public id: number;
public name: string;
// your stuff here
public myDefaultProp: string = "default value";
public constructor(init?: Partial<Customer>) {
Object.assign(this, init);
}
}
your return then would look like this:
return response.json().then(x => new Customer(JSON.parse(x)));
added an example https://stackblitz.com/edit/typescript-16wlmg
This essentially just a matter of determining what to do in order to create an instance of a class, and map the properties of a JSON response towards your custom class, and there could be many different ways to solve this,
But I think (Factory function) is appropriate approach for this kind of task.
I have a JSON object which I don't have control of and want to map it to a Java object which is pre-created.
There is one attribute in the JSON object which can be a URL or it could be a JSONArray.
Class SomeClass {
private URL items;
public URL getURL() {
return items;
}
public void setURL(URL url) {
this.items = url;
}
}
Below is the JSON:
Case A:
{
...
items: http://someurl.abc.com/linktoitems,
...
}
OR
Case B
{
...
items: [
{ "id": id1, "name": name1 },
{ "id": id2, "name": name2 }
]
...
}
If i create the POJO to map for Case A, Case B fails and vice versa. In short, is there a way to map the JSON attribute to the POJO field with different data types? In that case I will create two separate fields in the POJO named,
private URL itemLink;
private Item[] itemList;
It depends on exact details, but if what you are asking is if it is possible to map either JSON String or JSON array into a Java property, yes this can be done.
Obvious way would be to define a custom deserializer which handles both kinds of JSON input.
But it is also possible to define Java type in such a way that it can be constructed both by setting properties (which works from JSON Object) and have a single-String-arg constructor or static single-String-arg factory method marked with #JsonCreator.
Yet another possibility is to use an intermediate type that can deserialized from any JSON: both java.lang.Object and JsonNode ("JSON tree") instances can be created from any JSON. From this value you would need to do manual conversion; most likely in setter, like so:
public void setItems(JsonNode treeRoot) { .... }
What will not work, however, is defining two properties with the same name.
One thing I don't quite follow is how you would convert from List to URL though. So maybe you actually do need two separate internal fields; and setter would just assign to one of those (and getter would return value of just one).