comparing data in list of objects - dart

I have a JSON which returning a duplicate object if it has a different value for one of the attributes, for example:
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img1.JPG",
},
{
"nid": "41",
"news_title": "title",
"body": "body",
"news_image": "img2.JPG",
},
both of them are the same node with ID 41 and the other data are duplicated other than the unique which is news_image
The class of the object is:
String nid;
String newsTitle;
String body;
String newsImage;
List<String> newsImgs;
And am parsing it like this:
List<News> newsdata = (jsonResponse as List).map((i) => new News.fromJson(i));
Everything is fine till now .. but i have another list:
List<News> newsList = <News>[];
Where i want to add the images of the same news with the same nid to the list newsImgs and then add it to the newsList.. so i wont have duplicated news with the same nid and all of the images of the same news will be in one list
How to do this?

Try to make this list..
Set store only unique value..
Set<News> newsList= new Set();
newsList.addAll(newsdata);

Related

How do I create a new collection?

I'm building a chat app where there are GroupConversations and GroupMessages. Following the example of some of the Firestore YouTube videos, I've chosen to structure my data this way:
The ID of the GroupConversation is the ID for the collection of GroupMessages associated with that GroupConversation. Then inside of that document should be a new collection called Messages which holds documents.
Does that make sense or am I overcomplicating things? I can't seem to create that Messages collection or set anything to it in my Swift code
GroupConversations
id
title
desc
memberIds
GroupMessages
GroupConversationID
createdAt: Date // just because I need a key and a document?
Messages (new collection)
Message1
Message2
Message3
Thanks
Edit: Added Swift code
let db = Firestore.firestore()
var data: [String: Any] = [
"text": title,
"senderUsername": username,
"createdAt": Date(),
"updatedAt": Date()
]
let creationData: [String: Any] = [
"text": "Group Created",
"createdAt": Date()
]
let doc = db.collection("GroupMessages").addDocument(data: creationData)
db.document("GroupMessages/\(groupConvo.documentId)/\(doc.documentID)/messages").setData(data) { error in
if error == nil {
completion()
}
}
In my console, I'm seeing a new GroupMessage object created but not sub-collection of that GroupMessage called messages
You're not building the path to the document correctly. Document paths always alternate between collection and document names. To build a path to a document in a subcollection, it would go collection/document/subcollection/document. It looks like you've mixed up the last two elements in the string you're building.
In my opinion, it's harder to go wrong if you build up the document using methods rather than trying to build a string. Something like this:
db
.collection("GroupMessages")
.document(groupConvo.documentId)
.collection("Messages")
.document(doc.documentId)
.setData(...)

restassured - parsing response and searching by value

I have following REST API response:
"items":
[
{
"empid": "1234",
"name": "Santosh",
"hiredby": "Mark",
"date": "2017-01-31,00:19:41 PST",
},
{
"empid": "5678",
"name": "Kumar",
"hiredby": "Bob",
"date": "2017-01-31,08:30:31 PST"
}
]
My query is : - How do i get empid based on querying name as Kumar.
For example: I need to find "Kumar" name and get his empid. (that is, search by name and get his empid as response) I'm able to get the response and store it in Response object. but, from response object how can i traverse and query to get the required value.
Also,
I tried by retrieving as:
String name = get(REST_ENDPOINT).then().body("items.name",hasItems("Kumar")).extract().path("items.empid").toString();
when i print the response i get collection of the empid like [1234,5678], where as my expectation is to get only 5678.
Do I need to parse via JSONArray and JSONObject and iterate the response?
Please suggest.
You can use something like this
response1.jsonPath().getList("collect { it.credentials.findAll { it.credentialType == 'Ban User Name'}.credentialId }.flatten()")

Update multiple labels with values from a dictionary?

I'm trying to make an app that will select an index at random, something like 0-1000 and then print the key, value, and link of the selected number to three seperate labels on the iPhone simulator.
So from my example, I want to randomly select "0" or "1" and if for instance "1" was chosen; then the key, value, and link information would each be printed to three separate labels on the simulator. The following is what I've been working on in playgrounds. Is there a better way to go about this?
var spDictionary: [String: [String:String]] = [
"0": ["key": "AMZN", "value": "AMAZON", "link": "yahoo"],
"1": ["key": "AAPL", "value": "APPLE", "link": "yahoo2"],
]
And for the random aspect I think it would be something like this but I'm not sure? Sorry for the newbie question.
let randomIndex: Int = Int(arc4random_uniform(UInt32(spDictionary.count)))`
Even for small data structures it's worth it to create a custom class or struct
struct Data {
let key : String
let value : String
let link : String
}
Create an object
let data = Data(key: "AMZN", value: "AMAZON", link: "yahoo")
Get a property
let link = data.link
and you can declare your dictionary
var spDictionary : [String: Data] = ...

RestKit JSON Mapping

I have given JSON and cannot parse partial data. It seems dictionary into dictionary:
{
"products": [
{
"id": 6796,
"title": "my title",
"description": "desc",
"code": "12345",
"valueType": "null",
"discounts": [
{
"minPrice": null,
"maxPrice": null,
"value": 20,
"avail": false
}
]
}
]
}
I am using the latest version of RESTKit but I cannot properly parse under discounts.
my RestKit settings are:
responseMapping.addAttributeMappingsFromDictionary([
"id" : "id",
"code" : "code",
"title" : "title",
"valueType" : "valueType",
"description" : "desc",
"discounts.minPrice" : "minPrice",
"discounts.maxPrice" : "maxPrice",
"discounts.value" : "value",
"discounts.avail" : "avail",
])
but all values below discounts always return Nil. What I am doing wrong?
You can't directly map using discounts.XXX because discounts is an array and you have no way to index into that array and extract a single value.
You either need to change the source JSON to compress the values out of the dictionary, or create a custom object that you can map each item in the discounts array to.
Technically you could map the whole discounts array, which would give you an array of dictionaries, that you could then unpack in the setter method, but the array of custom objects is usually a better approach.

Invert a list of dictionaries to a dictionary of lists of objects with a particular key/value pair

Here is the file I'm parsing: https://raw.githubusercontent.com/pahnev/AirportJSON/master/CountriesAndAirports.json
{
"Airport": [
{
"AirportID": "1",
"Name": "Goroka",
"City": "Goroka",
"Country": "Papua New Guinea",
"IATA-FAA": "GKA",
"ICAO": "AYGA",
"Latitude": "-6081689",
"Longitude": "145391881",
"Altitude": "5282",
"Timezone": "10",
"DST": "U",
"tzdbtimezone": "Pacific/Port_Moresby"
},
{
"AirportID": "2",
"Name": "Madang",
"City": "Madang",
"Country": "Papua New Guinea",
"IATA-FAA": "MAG",
"ICAO": "AYMD",
"Latitude": "-5207083",
"Longitude": "1457887",
"Altitude": "20",
"Timezone": "10",
"DST": "U",
"tzdbtimezone": "Pacific/Port_Moresby"
},
....
I'm trying to create a list of the countries based on it, and then from that list, the airports in that country.
I know how to do all this and have done it with dummy data.
The problem is the JSON file as it has list of airports, which have the country name inside them. So when I try to parse this I get multiple values of one country.
_countryList = [json valueForKeyPath:#"Airport.Country"];
With this code I get list looking something like this:
Papua New Guinea
Papua New Guinea
Papua New Guinea
etc...
So can I somehow parse this and combine all same names of one country? Or do I have to heavily modify this database?
After getting a list of countries without duplicates I would like to be able to select a country from that and get the airports that are in that country.
So Papua New Guinea would show 6 airports, Greenland 4, and so on.
You can move your data through an NSSet to remove the duplicates -
NSArray *uniqueCountries=[[NSSet setWithArray:_countryList] allObjects];
Given a country you can then get the airports using filteredArrayUsingPredicate -
NSString *taregtCountry=#"Papua New Guinea";
NSPredicate *countryPredicate=[NSPredicate withFormat:#"Airport.Country==%#",targetCountry];
NSArray *airportsInCountry=[json filteredArrayUsingPredicate:countryPredicate];
An easy way to do this is to build a dictionary of arrays.
If [json valueForKeyPath:#"Airport.Country"] returns to you "Papua New Guinea", you can ask the dictionary to return to you the object for the key "Papua New Guinea". If you get back something (Array of airports), simply add the airport to that array. Otherwise you allocate a new array with that airport and set it to the dictionary under the country key.
The keys for the dictionary are the countries and the value for each key would be the array of airports. Since a dictionary does not hold duplicate keys, your data structure would match what you are trying to accomplish.

Resources