How to create Map<String, String> and Map<String, List<String> protobuf scala - scala

I am new to Scala and protobufs. I want to create a object something like this
{
"id": "usr-435-899",
"type": "SALES",
"filters": {
"country": [
"usa",
"germany"
],
"indication": [
"delivery"
]
}
}
So I think I cannot create the POJO like this in protobuf's.
Now I've created different JSON which is
{
"id": "usr-435-899",
"type": "SALES",
"filters": {
"country": {
"value": [
"usa",
"germany"
]
},
"indication": {
"value": [
"delivery"
]
}
}
}
So I've created a proto something like this:
message ListOfValues {
repeated string value = 1;
}
message AuditRequest {
required string id = 1;
required string type = 2;
map<string, ListOfValues> filters = 3;
}
But when I try to hit the api from POSTMAN it says 404 not found
Can anyone tell whats wrong in this? And Can we create proto for first JSON?

Related

play framework json lookup inside array

I have simple json:
{
"name": "John",
"placesVisited": [
{
"name": "Paris",
"data": {
"weather": "warm",
"date": "31/01/22"
}
},
{
"name": "New York",
"data": [
{
"weather": "warm",
"date": "31/01/21"
},
{
"weather": "cold",
"date": "28/01/21"
}
]
}
]
}
as you can see in this json there is placesVisited field, and if name is "New York" the "data" field is a List, and if the name is "Paris" its an object.
what I want to do is to pull the placesVisited object where "name": "New York" and then I will parse it to a case class I have, I can't use this case class for both objects in placesVisited cause they have diff types for the same name.
so what I thought is to do something like:
(myJson \ "placesVisited") and here I need to add something that will give me element where name is "New York", how can I do that?
my result should be this:
{
"name": "New York",
"data": [
{
"weather": "warm",
"date": "31/01/21"
},
{
"weather": "cold",
"date": "28/01/21"
}
]
}
something like this maybe can happen but its horrible haha:
(Json.parse(myjson) \ "placesVisited").as[List[JsObject]].find(item => {
item.value.get("name").toString.contains("New York")
}).getOrElse(throw Exception("could not find New York element")).as[NewYorkModel]
item.value.get("name").toString can slightly be simplified to (item \ "name").as[String] but otherwise there's not much to improve.
Another option is to use a case class Place(name: String, data: JsValue) and do it like this:
(Json.parse(myjson) \ "placesVisited")
.as[List[Place]]
.find(_.name == "New York")

Dart - Convert Map of objects fetched via HTTP REST-API

For my Calendar i get the following data as JSON from the Backend (*JAVA-Type = Map<LocalDate, List<Event>>):
{
"2022-05-28": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
}
],
"2022-05-27": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
},
{
"id": 1,
"title": "Testevent",
"fromDate": "2022-05-27T11:21:04.573754",
"toDate": "2022-05-27T12:21:04.573754",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "normal"
}
],
}
My Event Class looks like:
Class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
}
Now i need the same structure i had in the Backend (Map<DateTime, <List<Event>>) for my Calendar widget and i have no real clue on how to do it. I know how to convert json data into an object if i get a list of an object, but how can i store the date as key of the resulting map?
My code by now:
Future<Map<DateTime, List<Event>>> getEvents(DateTime _fromDate, DateTime
_endDate) async {
String _from = _fromDate.toString().split('.').first;
String _end = _endDate.toString().split('.').first;
final response = await get('${_url}calendar/events/$_from/$_end',
headers: {HttpHeaders.authorizationHeader: 'Bearer $_bearer'});
if (response.status.hasError) {
return Future.error('${response.statusText}');
} else {
final parsed = jsonDecode(response.body);
return parsed;
}
}
You need to do something like that:
var json = {...}; // <-- json obj
// method to parse data to map with list Event
dynamic fromJson(Map<String, dynamic> json){
var map = new Map();
json.keys.forEach((key){
// key is the date
map[key] = json[key].map((e) => Event.fromJson(e)).toList(); // <- need to create a method fromJson in your Event class
});
return map;
}
(...)
class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
fromJson(Map<String, dynamic> json) => Event(...); // <- parse json to Event class
}

How to put a conditional in json post request flutter

I have this payload that I need to send to a server
"members": [
{
"names": "ben",
"date-of-birth": "1978-01-01",
"gender": "Male",
"surname": "surname",
"role": "Partner",
"total-cut": "100.00"
}
],
Only thing is at times there are no members, and following this am not supposed to send the array at all, it should just be nothing at all, no members.
For clarification, this is an example only, think there is a members object, like the above, schools object, courses object, only at times some of this come up empty and consequently I should omit the empty object entirely.
For example, in the below, if there are no members,,
{
"members": [
{
"names": "ben",
"date-of-birth": "1978-01-01",
"gender": "Male",
"surname": "surname",
"role": "Partner",
"total-cut": "100.00"
}
],
"courses": [
{
"name": "ben",
"number": "32",
"teacher": "Russ",
"cut": "10.00"
}
],
}
how can i create a conditional that omits the members and leaves courses only
{
"courses": [
{
"name": "ben",
"number": "32",
"teacher": "Russ",
"cut": "10.00"
}
],
}
For context this is a post request
I don't know if this has been solved or not yet (I hope yes :P). But this is a practical approach for reference in case others do run into a similar issue.
Problem
Before, here is a problem rephrasing just to make sure we are on the same line. If you have members, add them to the map otherwise no. In both these conditions the map should look like this:
// With members
{
"members": [
{
"names": "member_name",
//...
}
],
"courses": [
{
"name": "course_name",
//...
}
],
}
// Without members
{
"courses": [
{
"name": "course_name",
//...
}
],
}
Solution
In my opinion, the best way to handle this is to declare an empty Map() and conditionally add entries to it as fellows:
Map<String, dynamic> buildMyMap(){
final buffer = <String, dynamic>{};
if(members.isNotEmpty){
// Option 1
buffer.addEntries(MapEntry("members", members));
// Option 2
buffer["members"] = members;
}else{
// (Optional) In case you want to delete pre-existing members
buffer.remove("members");
}
if(courses.isNotEmpty){
// Option 1
buffer.addEntries(MapEntry("courses", courses));
// Option 2
buffer["courses"] = courses;
}else{
// (Optional) in case you want to remove pre-existing courses!
buffer.remove('courses');
}
return buffer;
}
You should declare the parameter members to be optional in your API, then you have no need to send this parameter.
you can do the following
final List members = [];
final List courses = [];
final map = {
if (members.isNotEmpty)
'members': [
for (final member in members)
{
"names": "ben",
"date-of-birth": "1978-01-01",
"gender": "Male",
"surname": "surname",
"role": "Partner",
"total-cut": "100.00"
}
],
if (courses.isNotEmpty)
'courses': [
for (final course in courses)
{
"name": "ben",
"number": "32",
"teacher": "Russ",
"cut": "10.00"
}
]
};
you can use if statement inside a map or a list in flutter,
also, if you want to multiple fields if a condition is met
final map2 = {
if(true)...{
'name': 'name',
'age': '12'
} else ...{
'name': 'NO NAME',
'age': 'NO AGE'
}
};

How to pass a list of json to body of http Post request in Flutter?

I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.
submitQuestions() async {
var headers = {
'Content-Type': 'application/json',
'x-auth-token': '123edrfe33ewed'
};
var request = http.Request('POST', Uri.parse('url'));
request.body = json.encode({
"school_id": "123",
"teacher_id": "123",
"observer_id": "123",
"subject_id": "123",
"subject_name": "abc",
"class_id": "123",
"batch_id": "123",
"topic": "topic",
"academic_year": "2019-2020",
"remarks_data": [
{
"_id": "123",
"heading": "heading",
"Indicators": [
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 4
},
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 1
}
]
},
{
"_id": "123",
"heading": "abc",
"Indicators": [
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 3
}
]
}
]
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
}
This json will change dynamically when the number of questions increase. I cannot place this json file in the body like this. How to Do this one.
Wrap each list of json with jsonEncode
like:
"remarks_data": jsonEncode(..)
and do not forget to import.
import 'dart:convert';
The request body try to use Map data type. You can create a model class to deal with it.
Example
class School {
String school_id;
String teacher_id;
String observer_id;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['school_id'] = this.school_id;
data['teacher_id'] = this.teacher_id;
data['observer_id'] = this.observer_id;
...
return data;
}
}
/// Make sure your _school got data
School _school;
request.body = _school.toJson();

RestFB parsing many objects into one incorrectly

My restFB code results in writing on one App to my ArrayList. I need the arraylist to fill out properly with the number of appIds return in JSON. Any insights?
Here is my code:
public List<String> fetchAppIdsForUser() {
Connection<FacebookApp> appList = getClient().fetchConnection("me/applications/developer", FacebookApp.class);
List<String> appIds = new ArrayList<String> ();
for (List<FacebookApp> appListTwo : appList) {
for (FacebookApp app : appListTwo) {
appIds.add(app.getAppId());
}
}
return appIds;
}
And here is what is returned in JSON:
{
"data": [
{
"name": "x",
"namespace": "x",
"id": "x"
},
{
"name": "xx",
"namespace": "xx",
"id": "xx"
},
{
"name": "xxx",
"namespace": "xxxx",
"id": "xxxxx"
},
{
"name": "xxxx",
"namespace": "xxxxx",
"id": "xxxxx"
}
],
"paging": {
"next": "https://graph.facebook.com/xxxxx/applications?type=developer&format=json&access_token=XXXXXXXX"
}
}
I solved it using the following:
public List<String> fetchAppIdsForUser() {
Connection<FacebookApp> appList = getClient().fetchConnection("me/applications/developer", FacebookApp.class);
List<FacebookApp> list = appList.getData();
ArrayList<String> appNames = new ArrayList<String>();
for (FacebookApp app: list) {
appNames.add(app.getName());
}
return appNames;
}