How to retrieve data json api to form in flutter - flutter

I have a form textfield and dropdown and I have data productCode = "INQPREPAID50" i want to become 50000 in dropdown field "Nominal".
This my response json:
{
"responseCode": "0000",
"responseMessage": "Success",
"date": "20200320",
"time": "142352",
"currency": "IDR",
"content": {
"productCode": "INQPREPAID50",
"productName": "INQ Prabayar 50.000"
},
}
How to retrieve productCode = "INQPREPAID50" become to only number 50000 in dropdown "Nominal" and display data json api in next page screen. Please help me. Thanks.

You can use some function to parsing like
setNumber(String title) {
if (title.contains('50') {
return 50000;
} else {
return 0;
}
}
so just call in your text/widget example
Text("${setNumber(productCode)}",

Related

Go-MongoDriver decoding JSON array weirdly

Heyho party people,
I've recently took up learning Go and started working on a small side project which includes a API written using the Go Fiber library.
All the necessery data is stored in MongoDB with the following schema
{
"ObjectId": {
"name": "name",
"url": "url",
"dateAdded": "date",
"data": [{
"timestamp 1": "price 1"
},
{
"timestamp 2": "price 2"
}
]
}
}
The item type looks like this:
type Item struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Name string `json:"name" bson:"name"`
URL string `json:"url" bson:"url"`
DateAdded string `json:"dateAdded" bson:"dateAdded"`
Data []interface{} `json:"data" bson:"data"`
}
Whenever I query a stored item with
err = collection.FindOne(context.TODO(), filter).Decode(&item)
each map inside of the data-array is wrapped in another array =>
{ test url 2021-04-16 [[{2021-04-16 99.99}] [{2021-04-17 109.99}]] }
instead of
{ test url 2021-04-16 [{2021-04-16 99.99}, {2021-04-17 109.99}] }
Does anybody have an idea on how to fix this?
Thanks in advance!
OK, I've found a way to fix this behaviour for my use case.
As mentioned above, the MongoDB-driver for Go wraps each entry of an array into another respective array, which leads to a nested array.
After trying around for some time I found out, that inserting the document into your collection like the following example,
db.collection.insertOne({ name: "Name", url: "URL", dateAdded: "2021-04-25", data: { "2021-04-25": 9.99, "2021-04-26": 19.99 } })
then the result of a query performed in your program looks like this:
{ ObjectID("60858245f8805dc57a716500") Name URL 2021-04-25 [{ 2021-04-25 9.99 } { 2021-04-26 19.99 }] }
This means, that the JSON-schema should look like this
{
"ObjectId": {
"name": "name",
"url": "url",
"dateAdded": "date",
"data": {
"2021-04-25": 9.99,
"2021-04-26": 19.99
}
}
}
Sadly, I was not able to find out what is actually causing this odd behaviour, but I hope this helps anybody encountering this (or a similar) problem.
EDIT
Changing the type of the Data-field to []bson.M, as mkopriva said in the comments below, fixed it.
type Item struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Name string `json:"name" bson:"name"`
URL string `json:"url" bson:"url"`
DateAdded string `json:"dateAdded" bson:"dateAdded"`
Data []bson.M `json:"data" bson:"data"`
}
This way the original JSON-schema does not have to be adapted to the workaround.
{
"ObjectId":{
"name":"name",
"url":"url",
"dateAdded":"date",
"data": [
{
"2021-04-25": 9.99
},
{
"2021-04-26": 19.99
}
]
}
}

RXjava complicated async task

I am trying to use async rxjava flow to handle a complicated task.
I get list of metrics, and list of cities and get their values (list of date and value). Each metric is stored in a different db, so lots of HTTP calls are expected.
The result order means nothing so I want to:
run over all the metrics and asynchronously.
For every metric I want to run over all the cities asynchronously.
For every city and metric I want to create a HTTP call to fetch the data.
The end response should look like this:
"result": {
"metric1": [
{
"cityId": 8,
"values": [
{
"date": "2017-09-26T10:49:49",
"value": 445
},
{
"date": "2017-09-27T10:49:49",
"value": 341
}
]
},
{
"cityId": 9,
"values": [
{
"date": "2017-09-26T10:49:49",
"value": 445
},
{
"date": "2017-09-27T10:49:49",
"value": 341
}
]
}
],
"metric2": [
{
"cityId": 8,
"values": [
{
"date": "2017-09-26T10:49:49",
"value": 445
},
{
"date": "2017-09-27T10:49:49",
"value": 341
}
]
},
{
"cityId": 9,
"values": [
{
"date": "2017-09-26T10:49:49",
"value": 445
},
{
"date": "2017-09-27T10:49:49",
"value": 341
}
]
}
]
}
}
}
How can I achieve this? Got lost with all the observables. Which should be blocking, which should return a real value?
EDIT: added code sample
Here is what I have so far:
1. for each metric (parallel I guess):
Observable.from(request.getMetrics())
.subscribe(metric -> {
List metricDataList = getMetricData(metric, citiesList);
result.put(metric.getName(), metricDataList);
});
return ImmutableMap.of("result", result);
2. Get metric data (according to cities):
final List<Map<String,Object>> result = new ArrayList<>();
Observable.from(citiesList).subscribe(city ->
result.add(ImmutableMap.of(
"id", city.getId(),
"name", city.getName(),
"value", getMetricValues(metricType, city.getId())
.toBlocking()
.firstOrDefault(new ArrayList<>()))));
return result;
3. According to metric I decide which service to invoke:
private Observable<List<AggregatedObject>> getMetricValues(AggregationMetricType metric, Integer cityId) {
switch (metric) {
case METRIC_1: return fetchMetric1(city);
case METRIC_2: return fetchMetric2(city);
}
return Observable.empty();
}
4. Invoke the service:
public Observable<List<AggregatedObject>> fetchMetric1(Integer city) {
return Observable.just(httpClient.getData(city)
.map(this::transformCountResult)
.onErrorResumeNext(err -> Observable.from(new ArrayList<>()));
}
5. Transform the received data:
protected List<AggregatedObject> transformCountResult(JsonNode jsonNode) {
...
}
It is working, though I am not sure that I have implemented it correctly regarding blocking and concurrency.
Help please.
Regards,
Ido
In the step you call "2) get metric data", you could refactor as
final List<Map<String,Object>> result = new ArrayList<>();
Observable.from(citiesList)
.flatMap(city -> getMetricValues(metricType, city.getId())
.firstOrDefault(new ArrayList<>())
.map( metric -> ImmutableMap.of(
"id", city.getId(),
"name", city.getName(),
"value", metric) ) )
.toList()
.toBlocking()
.subscribe( resultList -> result = resultList );
Moving the toBlocking() outside of the processing means that individual requests will occur in a more parallel fashion.

Elasticsearch for normalized data

I have some data from facebook api's...
I have a FB page and thats part of multiple country...
For example:-
Assume company-x operated in multiple countries - USA, UK, India, China
Now, a page can be posted on multiple country pages.
For example:- Company-x new innovation will be displayed in all the 4 country pages...
Each of the pages will get its over comments, likes...etc...
So, basically its a relational data.
Company(1) - Country(n)- Post(n) - LIkes(n) - Comments(n)...
I would like to know what would be the best way to store this data in elastic search and implement the search engine..
As you can't use "classic" (relational) JOINs in Elasticsearch, IMHO you only can choose between storing the (sub-)objects as flat objects, parent-child objects or nested objects in the index/type.
I think that you should consider the first two option. I personally would opt for flat objects, as they are easier to load, and also get returned from the FB Graph API in that way ("flat"). What you would have to add in you application is the mapping of the page to Company -> Country, because FB doesn't know about that.
See
https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-mapping.html
https://www.elastic.co/guide/en/elasticsearch/guide/current/parent-child-mapping.html
As a query for the posts, you could use something like
/?ids={page1_id},{page2_id},{page3_id}&fields=id,posts.fields(id,message,created_time,link,picture,place,status_type,shares,likes.summary(true).limit(0),comments.summary(true).limit(0))
which will return something like
{
"id": "7419689078",
"posts": {
"data": [
{
"id": "7419689078_10153348181604079",
"message": "Gotta find them all in the real world soon.",
"created_time": "2015-09-10T06:40:12+0000",
"link": "http://venturebeat.com/2015/09/09/nintendo-takes-pokemon-into-mobile-gaming-in-partnership-with-google-niantic/",
"picture": "https://fbexternal-a.akamaihd.net/safe_image.php?d=AQDvvzpCAM1WkJZS&w=130&h=130&url=http%3A%2F%2Fi0.wp.com%2Fventurebeat.com%2Fwp-content%2Fuploads%2F2013%2F04%2Fpokemon_mystery_dungeon_gates_to_infinity_art.jpg%3Ffit%3D780%252C9999&cfs=1",
"status_type": "shared_story",
"likes": {
"data": [
],
"summary": {
"total_count": 0,
"can_like": true,
"has_liked": false
}
},
"comments": {
"data": [
],
"summary": {
"order": "ranked",
"total_count": 0,
"can_comment": true
}
}
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.4/7419689078/posts?fields=id,message,created_time,link,picture,place,status_type,shares,likes.summary%28true%29.limit%280%29,comments.summary%28true%29.limit%280%29&limit=1&since=1441867212&access_token=&__paging_token=&__previous=1",
"next": "https://graph.facebook.com/v2.4/7419689078/posts?fields=id,message,created_time,link,picture,place,status_type,shares,likes.summary%28true%29.limit%280%29,comments.summary%28true%29.limit%280%29&limit=1&access_token=&until=1441867212&__paging_token="
}
}
}
You can then use some application-side JSON manipulation to
Add the Company -> Country -> Page mapping info to the JSON
Get rid of unwanted fields such as paging
Flatten the structure before saving (e.g. posts.data as posts)
before you save it to Elasticsearch. See the JSFiddle I prepared (fill in the access token!):
http://jsfiddle.net/7x9xuo8L/
Then, you can use the bulk load feature to load the data to Elasticsearch:
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
Sample JavaScript code:
var pageMapping = {
"venturebeat": {
"country": "United States",
"company": "Venture Beat"
},
"techcrunch": {
"country": "United States",
"company": "TechCrunch"
}
};
//For bulk load
var esInfo = {
"index": "socialmedia",
"type": "fbosts"
};
var accessToken = "!!!FILL_IN_HERE_BEFORE_EXECUTING!!!";
var requestUrl = "https://graph.facebook.com/?ids=venturebeat,techcrunch&fields=id,name,posts.fields(id,message,created_time,link,picture,place,status_type,shares,likes.summary(true).limit(0),comments.summary(true).limit(0)).limit(2)&access_token=" + accessToken;
$.getJSON(requestUrl, function(fbResponse) {
//Array to store the bulk info for ES
var bulkLoad = [];
//Iterate over the pages
Object.getOwnPropertyNames(fbResponse).forEach(function(page, idx, array) {
var pageData = fbResponse[page];
var pageId = pageData.id;
pageData.posts.data.forEach(function(pagePostObj, idx, array) {
var postObj = {};
postObj.country = pageMapping[page].country;
postObj.company = pageMapping[page].company;
postObj.page_id = pageData.id;
postObj.page_name = pageData.name;
postObj.post_id = pagePostObj.id;
postObj.message = pagePostObj.message;
postObj.created_time = pagePostObj.created_time;
postObj.link = pagePostObj.link;
postObj.picture = pagePostObj.picture;
postObj.place = pagePostObj.place;
postObj.status_type = pagePostObj.status_type;
postObj.shares_count = pagePostObj.shares.count;
postObj.likes_count = pagePostObj.likes.summary.total_count;
postObj.comments_count = pagePostObj.comments.summary.total_count;
//Push bulk load metadata
bulkLoad.push({ "index" : { "_index": esInfo.index, "_type": esInfo.type } })
//Push actual object data
bulkLoad.push(postObj);
});
});
//You can now take the bulkLoad object and POST it to Elasticsearch!
console.log(JSON.stringify(bulkLoad));
});

Sorting by document values in couchbase and scala

I am using couchbase and I have a document (product) that looks like:
{
"id": "5fe281c3-81b6-4eb5-96a1-331ff3b37c2c",
"defaultName": "default name",
"defaultDescription": "default description",
"references": {
"configuratorId": "1",
"seekId": "1",
"hsId": "1",
"fpId": "1"
},
"tenantProducts": {
"2": {
"adminRank": 1,
"systemRank": 15,
"categories": [
"3"
]
}
},
"docType": "product"
}
I wish to get all products (this json is product) that belong to certain category, So i've created the following view:
function (doc, meta) {
if(doc.docType == "product")
{
for (var tenant in doc.tenantProducts) {
var categories = doc.tenantProducts[tenant].categories
// emit(categories, doc);
for(i=0;i<categories.length;i++)
{
emit([tenant, categories[i]], doc);
}
}
}
}
So i can run the view with keys like:
[["tenantId", "Category1"]] //Can also have: [["tenant1", "Category1"],["tenant1", "Category2"] ]
My problem is that i receive the document, but i wish to sort the documents by their admin rank and system rank, these are 2 fields that exists in the "value".
I understand that the only solution would be to add those fields to my key, determine that my key would be from now:
[["tenantId", "Category1", "systemRank", "adminRank"]]
And after i get documents, i need to sort by the 3rd and 4th parameters of the key ?
I just want to make sure i understand this right.
Thanks

Web API returns XML and Json, only want Json

Hi I am trying to create web api that I can call to view all the documents in the MongoDB, now the documents are very large and are heavily nested, I have Managed to return the document but in Json with the headers in XML.
I need to return this entire thing in Json!
This code takes the BsonDocument Product and returns this as Json because without this I get an error:
[JsonIgnore]
public BsonDocument Product { get; set; }
[DataMember]
public string Product
{
get { return Product .ToJson(); }
set { Product = BsonDocument.Parse(value); }
}
Here is a sample of the Document(This is a basic example, the actual document is much larger with deeper levels:
{
"product": {
"Type": "Phone",
"Size": {
"Height": 10,
"Lenght": 5,
"Weight": 30
}
"Make": "Apple"
"Model": {
"Name": "IPhone",
"Range": "4s"
}
}
}
it returns as
<Product>
{"product": {"Type": "Phone","Size": {"Height": 10,"Lenght": 5,"Weight": 30}"Make": "Apple", "Model": {"Name": "IPhone","Range": "4s"}}}
</Product>
How do i fix this?
How do i fix this?
Like this:
public HttpResponseMessage Get()
{
MyViewModel model = ...
// This will contain the JSON you want to return to the client
string product = model.Product;
var response = new HttpResponseMessage();
response.Content = new StringContent(product, Encoding.UTF8, "application/json");
return response;
}