How to convert reddit posts to list in dart? - json

I want to get posts from Reddit API. Posts are in "children" node but each object has another object inside.
Can somebody help me write a function that convert this JSON to a list of dart objects?
Here is JSON string.
{
"kind": "Listing",
"data": {
"after": "t3_zzzhq4",
"dist": 2,
"children": [
{
"kind": "t3",
"data": {
"selftext": "blablabla",
"author_fullname": "3xblabla",
"title": "moreblabla",
"created": 1672515982,
"id": "10020p0"
}
},
{
"kind": "t3",
"data": {
"selftext": "blablabla",
"author_fullname": "3xblabla",
"title": "moreblabla",
"created": 1672515982,
"id": "10020p0"
}
}
],
"before": null
}
}
I tried all the tutorials on the topic of complex json parsing, but none of them met my needs. I would know how to parse simple json, but here it is deeply nested JSON, which bothers me a lot, and i cant quite grasp it. Appreciete any help.
Solution:
First go to json to dart and paste JSON string, this generator will make you all classes needed for your JSON.
Then you will need to decode string:
final jsonResponse = json.decode(jsonString);
And then deserialize your JSON like this:
List postslist = list.map((i) => Post.fromJson(i['data'])).toList();
For me, it was crucial i['data']. After adding that, i could deserialize all objects that were living inside that node. Thanks everyone! Hope that someone else this will be helpful! Cheers.

Related

Unable to Parse Array from Returned JSON using Moshi

I've started using Moshi along with Retrofit 2 and have run into an issue parsing an array of objects within the parent object that is returned from the service call. The returned JSON looks like this:
{
"acf": {
"email": "dirk#dirkgently.com",
"address": "24 Cortland Avenue",
"country": "US",
"description": "Oh my goodness",
"created_at": "1416672067",
"updated_at": "1416672067",
"facebook": "",
"contact": "Dirk Gently",
"photos": [
{
"file": 3525
},
{
"file": 3526
},
{
"file": 6110
},
{
"file": 3527
},
{
"file": 3528
},
{
"file": 6700
},
{
"file": 7404
},
{
"file": 7419
}
],
"latitude": "40.801249",
"longitude": "-99.746280"
}
}
I'm getting the following exception with the 'photos' field:
com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was
STRING at path $[0].acf.photos
I've defined the models like so:
public class Acf {
private String email;
private String address;
List<Photo>photos;
}
public class Photo {
public int file;
}
I've tried declaring the property in the model in various other ways, and read through the docs to try to figure out what I'm doing wrong. I'm stuck at this point and could really use a second set of eyes to point me in the right direction. I have a feeling I'm missing something painfully simple and obvious. Thanks in advance to anyone that can help. If I've left out any pertinent info let me know and I'll update the post.
Update: I've found that this exception only occurs when I fetch multiple ACFs. If I do a request for a single object everything parses correctly.
Based on the error it sounds like the endpoint you're calling is possibly returning different types for that parameter (i.e. a string when you're expecting an array). Try changing it from a List<> to an Object and see if the call succeeds. You should be able to type-check the Object and cast whatever you need from it. An alternative would be to use a custom type adapter, but I'm not sure how to accomplish that using Moshi. Good luck.

Microsoft.Graph Unable to deserialize the response

I am quite new to programming and especially Microsoft.Graph
I am having problems handling the response to:
https://graph.microsoft.com/v1.0/me/drive/root/children
the response looks like this (just much longer):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('xyz%40hotmail.com')/drive/root/children",
"value": [
{
"createdBy": {
"user": {
"displayName": "xyz",
"id": "cf58e4781082"
}
},
"createdDateTime": "2009-01-08T08:52:07.063Z",
"cTag": "adDpFREJDR4RTQMTgxMDgyITEyOC42MzYxODM0MTU0Mjc3MDAwMDA",
"eTag": "aRURCQ0Y1OEU0A4MiExMjguMA",
"id": "EDBCF58E471082!128",
"lastModifiedBy": {
"user": {
"displayName": "xyz",
"id": "edbcf58e48082"
}
}, ............. etc...
The response that I received is correct, in JSON format (I believe ><), but I cannot figure out how to parse it into an array containing the folders name.
Please help!
Have considered using the Microsoft Graph client library? It will deserialize the JSON. Your call will look like this:
// Return all children files and folders off the drive root.
var driveItems = await graphClient.Me.Drive
.Root
.Children
.Request()
.GetAsync();
foreach (var item in driveItems)
{
// Get your item information
}
Here's some samples to help you get started:
https://github.com/microsoftgraph?utf8=%E2%9C%93&q=csharp
You can use the JavaScriptSerializer to do this. Assuming
//json contains the JSON Response
var jsonOutput = new System.Web.Script.Serialization.JavaScriptSerializer();
jsonOutput.DeserializeObject(json);
This has been discussed earlier. See this thread: Easiest way to parse JSON response
Refer this link for JavaScriptSerializer: https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

Reading complex json data without iteration

I am working with some data and often the data is nested and i am required to perform some CRUD operations based on the structure of the data i have. For instance i have this json structure
{
"_id": "KnNLkJEhrDsvWedLu",
"createdAt": {
"$date": "2016-10-13T11:24:13.843Z"
},
"services": {
"password": {
"bcrypt": "$2a$30$1/cniPwPNCuwZ/MQDPQkLej..cAATkoGX.qD1TS4iHgf/pwZYE.j."
},
"email": {
"verificationTokens": [
{
"token": "qxe_T9IS7jW7gntpK0Q7UQ35RJ9jO9m2lclnokO3z87",
"address": "drwho#gmail.com",
"when": {
"$date": "2016-10-13T11:24:14.428Z"
}
}
]
},
"resume": {
"loginTokens": []
}
},
"username": "doctorwho",
"emails": [
{
"address": "drwho#gmail.com",
"verified": false
}
],
"persodata": {
"lastlogin": {
"$date": "2016-10-13T11:29:36.816Z"
},
"fname": "Doctor",
"lname": "Who",
"mobile": "+4480000000",
"identity": "1",
"email": "drwho#gmail.com",
"gender": null
}
}
I have several data sets with such complex structure. I need to read the data, edit and also delete. Before i get to iteration, i was wondering how i can read the data without iteration then iterate when i absolutely have to.
What are the rules i should keep in mind when reading such complex json structures to enable me read any complex structure i come across?.
I am currently using javascript but i am looking for rules that apply in other languages as well.
Parsing Json in JavaScript should be easy. http://www.json.org/js.html.
"Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure". Just follow the examples on that page.
If you want to use another language, in Java you could use Jackson or Gson to map those json strings to objects. Then using them becomes easy. Both libraries are annotation based, and wouldn't be difficult to implement.

Siesta: Child resources

I am having difficulties understanding how does Siesta figure out the child of a resource. For example I have the following events resource:
JSON returned by "/events"
{
"success": 1,
"events": [
{
"id": 1,
"type": "meeting",
"eventDate": "2015-08-20",
"notes": "fadsfasfa",
"title": null
},{
"id": 2,
"type": "game",
"eventDate": "2015-08-31",
"notes": "fdsafdf",
"title": null
}
]
}
Sadly, calling "/events/1" for example, does not return the event with id=2. Is there a way to tell Siesta which event has the id=2?
Suppose you have:
let events = myService.resource("/events")
Then you can navigate from the /events resource to the /events/2 resource like this:
let event = events.child("2")
That will give you the same object as if you had asked for myService.resource("/events/2").
To extract that 2 from the JSON, use normal Swift JSON parsing techniques. (Siesta doesn’t apply any special inspection or interpretation to the JSON once it’s parsed.) I recommend using the SwiftyJSON library for easier JSON traversal. For example, it lets you do something like this to extract those event IDs and get the child resources:
let allEventResources =
JSON(events.jsonDict)["events"]
.arrayValue
.flatMap { $0["id"].string }
.map(event.child)

Assembling complex multidimensional dictionaries dynamically for JSON in Swift

I'm trying to assemble some complex JSON like the following dynamically:
{
"data": {
"attributes": {
"duration_sec": 200
},
"relationships": {
"address": {
"data": {
"id": 1,
"type": "addresses"
}
}
}
},
"included": [
{
"type": "addresses",
"id": null,
"attributes": {
"zip_code": "90210"
}
}
]
}
That is, I have an array of Address structs that I need to loop through to assemble the relationships and included. I would prefer if this were a dictionary, but I could also use SwiftyJSON to just assemble JSON object instead.
When I tried doing this myself, I kept having issues with ambiguity from the compiler, so I honestly don't know how to tackle this problem. I come from dynamic programming languages so am feeling just generally flummoxed by this.
Hard to answer that one without exact compiler error, but usually errors about ambiguity come from the fact that you're trying to create a heterogeneous dictionary and compiler is not able to infer it's type.
In case you want to create a json object like the one above and have use JSON(dictionary:) initializer you should declare a type of dictionary manually as [String: AnyObject]
example:
let exampleDict: [String: AnyObject] = ["one" : 1, "two": "two", "three": [1, 2, 3]]