Failed to denormalize attribute "date" value for class - api

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;
}
//..
}

Related

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.

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();

Laravel Carbon error data missing with casting

I have a date property, and I try to cast it to the DateTime format during saving.
protected $casts = [
'date' => 'datetime:Y-m-d H:m',
];
In my controller, I have the following method.
public function change(int $gameSerieId, Request $request)
{
try {
$gameSerie = GameSerie::findOrFail($gameSerieId);
$gameSerie->update($request->all());
return response()->json('ok');
} catch (\Exception $exception) {
throw new GameApiException('Something went wrong!');
}
}
However, I get an error "Data Missing" because my date input format looks like a string: 2019-11-17 21:00.
I have found the ability of use mutators for set attributes
public function setDateAttribute($date)
{
$this->attributes['date'] = Carbon::make($date);
}
https://laravel.com/docs/5.7/eloquent-mutators#defining-a-mutator

How to add custom serialization/deserialization for protobuf?

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

Set field to a shared value

I have a class that looks like this:
class Data {
#JsonCreator
public Data(#JsonProperty("string") String s, Widget w) {
string = s;
widget = w;
}
String string;
Widget widget;
}
I want to deserialize it from this from JSON like
{
"string": "string value"
}
When deserializing, I want to set widget to a shared instance. I have that instance when I create the object mapper, but I can not see how to tell Jackson to use this instance.
I see JsonDeserialize.getNullValue and getEmptyValue, but those look like they are for handling
{
"string": "string value", "widget": null
}
which is not the JSON that I have.
You could try #JacksonInject:
public class Data {
#JacksonInject
public Widget widget;
...
}
And then use as follows:
Widget widget = ...
InjectableValues injectable = new InjectableValues.Std().addValue(Widget.class, widget);
Data data = new ObjectMapper().reader(injectable).forType(Data.class).readValue(json);