How to add custom serialization/deserialization for protobuf? - serialization

I have my message definition like
message ID {
string value = 1;
}
message User {
ID id = 1;
google.protobuf.StringValue name = 2;
}
Now if I serialize an instance of User to json, I get something like this
{
"id": {
"value" : "myid"
}
"name" : "Josh"
}
As you can see for the WKT types the value is unnested. However, for my custom message type User the value is nested. How do I make the output look like
{
"id": "myid"
"name" : "Josh"
}
I mean how do I serialize, deserialize to custom type.
One option I could think of is update this function https://github.com/protocolbuffers/protobuf/blob/master/python/google/protobuf/json_format.py#L199
This means, have a copy of json_format.py and extend _IsWrapperMessage to my custom types

Related

How do I pass a json body request to api in a map string data structure in Golang?

I am new to golang and grpc, need guidance and clarification. I have below definition as a parameter to call a POST request for an external API.
params := map[string]string{
"movie": movie,
"seat": seat,
"pax": fmt.Sprint(pax),
"class": class,
}
In proto file, I have below:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
TicketData data= 1;
}
However in POSTMAN (grpc request), the body request is showing below:
{
"data":
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
}
the request body should be below:
{
"data": **[**
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
**]** - missing brackets in my json body
}
I have tried using structpb and also map string interface. It doesn't seem to work. Any pointer will be appreciated. Thank you.
You want the data field to be repeated TicketData.
See e.g. Specifying Field Rules in the Protobuf Language Guide (proto3).
Specifically:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
repeated TicketData data= 1;
}
NOTE Although you include protobuf definitions, your examples are JSON. Protobuf implementations usually include automatic mappings between protobuf and JSON which is -- I assume -- what you're presenting.

How to make api call of string in flutter?

I am learning Flutter. This is the string that I need to call and I don't know how to call this type of string.
{
"Info":[
{
"c_type_id":"1",
"cleaning type":"Washroom Cleaning"
},
{
"c_type_id":"2",
"cleaning type":"Garden\/Lawn Cleaning"
}
]
}
My code
class Album {
final String title;
Album({
this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
title: json['title'],
);
}
}
As I am following my code like this https://flutter.dev/docs/cookbook/networking/fetch-data
and got this error "A non-null String must be provided to a Text widget." because they are following this type of string and my string type is different. Help!
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
}
Your given data (API response) seems to have a list of maps, so you should get the data first (use async function):
var response = await http.get("Your Url")
then you should extract the given map list as follow:
var temp = json.decode(response);
List<dynamic> result = temp['Info']); // it is the described list
now, you can use your data (extract each parameter):
String c_type_id = result[0]['c_type_id'];
// and so on...
Your question is not clear at all but I can show you an example how to reach an element in a json.
Your json consists a list that contains string keys. To reach first element of list;
json["Info"][0]
Then pass the key you want to get its value;
json["Info"][0]["c_type_id"]
http_requests All type of http requests are mentioned in this post. If you have any further problem kindly make comment.

Failed to denormalize attribute "date" value for class

I am trying to save by API an object given by the Front in React JS
So I have this object testing in Insomnia:
{
"rate": 1.59,
"correction":"2 ui nOVORAPID",
"date": "2020-11-26",
"time": "7:30"}
I don't understand why i have the error
Failed to denormalize attribute "date" value for class "App\Entity\Bloodsugar": Expected argument of type "string", "object" given at property path "date".
My controller:
$user = $this->getUser();
$jsonReceived = $request->getContent();
$json = json_decode($jsonReceived);
$newBloodsugar = $serializer->deserialize($jsonReceived, BloodSugar::class, 'json');
...
I guess that Symfony does not recognize the date format "Y-m-d", how can I do so ?
I guess your BloodSugar class has invalid setter or property type. Normally symfony-serializer normalize dates to Datetime, while your entity is expecting string. Try to change it to DatetimeInterface, smth like this:
class BloodSugar {
//..
private ?DatetimeInterface $date;
//..
public function setDate(DatetimeInterface $date){
$this->date = $date;
return $this;
}
//..
}

How to change JSON returned by query using Helidon 2.0.0-M-2

I'm using Helidon 2.0.0-M2.
When I run the query below I get back a list of JSON objects.
dbClient.execute(exec -> exec.createNamedQuery("select-dsitem-by-id")
.addParam("userId", dataItemId)
.execute())
.thenAccept(response::send)
.exceptionally(throwable -> sendError(throwable, response));
Returned list
[
{
"data": "qwerty",
"user_id": "12345"
},
{
"data": "qwerty123",
"user_id": "22345"
}
]
The attribute names seem to be taken directly from the database column name. e.g. one attribute name returned is "user_id". However, I want it to be "userId". I also want to create a parent wrapper for this list like:
{
"userList": [
{
"data": "qwerty",
"user_id": "12345"
},
{
"data": "qwerty123",
"user_id": "22345"
}
]
}
What is the best way to do this with the dbclient?
Thanks
Simple approach:
Change your SQL statement to return the correct name, such as:
SELECT data, user_id as userId FROM mytable
Complicated approach:
We are working on a better support to map to a JSON stream.
Currently there is only one (a bit complicated) way to achieve this:
You can create a custom mapper from a DbRow to JsonObject. This mapper needs to be a general one (it must work for any DbRow of any query).
The built-in mapper uses metadata provided on the columns. I have prepared a simple example (that just expects to have a single type of statements):
class DbRecordMapperProvider implements DbMapperProvider {
private static final DbMapper<JsonObject> MAPPER = new DbRecordMapper();
#SuppressWarnings("unchecked")
#Override
public <T> Optional<DbMapper<T>> mapper(Class<T> aClass) {
if (JsonObject.class.equals(aClass)) {
return Optional.of((DbMapper<T>)MAPPER);
}
return Optional.empty();
}
}
class DbRecordMapper implements DbMapper<JsonObject> {
#Override
public JsonObject read(DbRow dbRow) {
return Json.createObjectBuilder()
.add("name", dbRow.column("FIRSTPART").as(String.class))
.add("message", dbRow.column("SECONDPART").as(String.class))
.build();
}
#Override
public Map<String, ?> toNamedParameters(JsonObject dbRecord) {
return dbRecord;
}
#Override
public List<?> toIndexedParameters(JsonObject dbRecord) {
throw new IllegalStateException("Cannot convert json object to indexed parameters");
}
}
The important method is public JsonObject read(DbRow dbRow).
Once you have such a DbMapperProvider, you register it with the DbClient:
dbClient = DbClient.builder()
.config(config.get("db"))
.mapperProvider(new DbRecordMapperProvider())
.build();

How to get the value of an annotated variable?

So, I'm writing a method that will get annotated variables (doubles) and store them in a map. The variables are elements of an object. The name of the variable should be the key and its value - the parameter.
public void putInMap() {
Field[] fields = this.getClass().getDeclaredFields();
for (Field v: fields) {
if (v.isAnnotationPresent(Annotation.class))
map.put(v.getName(), *value here* );
}
}
My question is how to get the value of the variable (which is now a Field) so that I could put it in my map?
Try:
for (Field v : fields) {
if (v.isAnnotationPresent(Annotation.class)) {
v.setAccessible(true);
map.put(v.getName(), v.get(this));
}
}