Why fromJson() function of Protobuf not working in Dart - flutter

I have an issue with the fromJson() function.
I try to build my protobuf with the data received from Firestore and the fromJson() seems to not be able to parse it.
Facing this issue, I decide to do a test by creating a new empty Protobuf manually, export it as a JSON and create a new protobuf with the json. I got some weird issues:
MyProtobuf my_protobuf = MyProtobuf();
my_protobuf.id = "ABC";
...
// Exporting using writeToJson()
String json1 = my_protobuf.writeToJson(); // All my keys are numbers.. why?
// Exporting using a Map
Map<String, dynamic> json2_map = info_to_write.toProto3Json();
String json2 = JsonEncoder().convert(json2_map); // Seems to be a normal JSON
// Build a protobuf from JSON
MyProtobuf new_protobuf1 = MyProtobuf.fromJson(json1); // Exception thrown
MyProtobuf new_protobuf2 = MyProtobuf.fromJson(json2); // Exception thrown
Is this a bug of Im not using this good function?
This is my proto file:
syntax = "proto3";
package test.v1;
message MyProtobuf {
string id = 1;
string name = 2;
}

To convert a message to json string, you need to use the following code:
MyProtobuf my_protobuf = MyProtobuf();
my_protobuf.id = "ABC";
...
// convert to json object
var obj = my_protobuf.toProto3Json();
// encode to json string
var value = jsonEncode(obj);
To decode json string to protobuf message, use the following:
var jsonString = ".....";
// decode to json object
var obj = jsonDecode(docJson);
var my_protobuf = MyProtobuf.create()..mergeFromProto3Json(obj);
see https://github.com/google/protobuf.dart/issues/220#issuecomment-863250957

Related

Flutter/Dart convert a string formated as an object into a array

I am attempting to convert a string that is formatted as an object but with no luck, the data is originally formatted as a _CompactLinkedHashSet<String> so i tried to convert it to a json thinking that an array will be the output, below is my code.
var items = dataColumn[index]['items'];
final item = json.decode(json.encode(items.toString()));
When i print(items.runtimeType) the items is equals to _CompactLinkedHashSet<String>
but manage to convert it to a string using json encode and decode but the output is not an array its a string formatted as below
{'Word-1', 'Word-2', 'Word-3'}
I would like to convert it to an array so i can display it inside a ListView.builder like below
['Word-1', 'Word-2', 'Word-3']
You can change like below.
void main() {
var item = {'Word-1', 'Word-2', 'Word-3'};
print(item.runtimeType);
print(item);
// var itemList = item.map((item) => item).toList();
var itemList = List.from(item);
print(itemList.runtimeType);
print(itemList);
}

Dart Convert HTML to JSON

The official Turkey's Dictionary has some kind of json request system but the response it gave is HTML, not JSON.
Example:
https://sozluk.gov.tr/gts?ara=kalem
I'm trying to convert this HTML to JSON but couldn't make it. When I use html plugin on Flutter it gives me some kind of #document every time.
var sozlukurl = await http.Client()
.get(Uri.parse('https://sozluk.gov.tr/gts?ara=$ceviri'));
print(sozlukurl);
var sozlukapibody = parse(sozlukurl.body);
print(sozlukapibody);
var decoded = json.decode(sozlukapibody.toString());
var sozlukbilgi = jsonDecode(utf8.decode(decoded.bodyBytes)) as Map;
var sozlukanlam = sozlukbilgi['anlamlarListe'][0]['anlam'];
print(sozlukanlam);
Output from sozlukurl:
I/flutter ( 5350): Instance of 'Response'
Output from sozlukapibody:
I/flutter ( 5350): #document
Final Error:
FormatException (FormatException: Unexpected character (at character 1)
#document
^
)
How can i solve this problem?
It returns a json with an array encapsulating it. For your particular example jsonDecode should work fine, just take index 0 of the array to access the json.
var res = await http.Client()
.get(Uri.parse('https://sozluk.gov.tr/gts?ara=kalem'));
var body = res.body;
var decoded = jsonDecode(body);
var json = decoded[0];
var sozlukanlam = json["anlamlarListe"][0]["anlam"];
print(sozlukanlam);
I tried it on DartPad and not on an actual app however.

Base64 string reduces after putting Map (data structure) into json.decode(map)

I am converting an Image to base64 and then I am putting it into the Map data structure, but when I convert Map into the JSON string, base64 string reduces and gets the reduced length response from the server. My question is why is Map reducing it?
"Message": "Invalid length for a Base-64 char array or string."
Converting Image file to Base64
var imageBytes = pfImage.readAsBytesSync();
String base64Image = base64Encode(imageBytes);
print("base64 is =$base64Image");
putting into the map
var petData = Map<String, dynamic>();
petData['user_id'] = 55;
petData['name'] = "sdf";
petData['breed'] = "dsf";
petData['StrImageBase64'] =base64Image != null ? base64Image : "";
converting to json string
print("map>>" + json.encode(map));
Some More Info
I have checked it locally as well by putting base64string into map and then print it, the result is in reduced string.
petData['StrImageBase64'] ="/9j/4AAQSkZJRgABAQAAAQABAAD/4RllRXhpZgAASUkqAAgAAAAHABoBBQABAAAAYgAAABsBBQABAAAAagAAACgBAwABAAAAAgAAADIBAgAUAAAAcgAAABMCAwABAAAAAQAAAGmHBAABAAAAhgAAACWIBAABAAAA6AAAACoBAABIAAAAAQAAAEgAAAABAAAAMjAxOToxMToxMCAwNTo1NTozMwAHAACQBwAEAAAAMDIxMAGRBwAEAAAAAQIDAAqSBQABAAAA4AAAAACgBwAEAAAAMDEwMAGgAwABAAAA//8AAAKgBAABAAAAAAUAAAOgBAABAAAAwAMAAAAAAAAkEwAA6AMAAAIABwAFAAMAAAAGAQAAHQACAAsAAAAeAQAAAAAAAAAAAAABAAAANwAAAAEAAAAfAAAAAQAAADIwMTk6MTE6MTAAAAIAAQIEAAEAAABIAQAAAgIEAAEAAAAVGAAAAAAAAP/Y/+AAEEpGSUYAAQEAAAEAAQAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgA8AFAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX2";
print("json.encode =${json.encode(petData)}");
UPDATED
It is not possible, that the map can reduce the value, or Json.decode(map) returns the reduced base64 string, Actually its VS code editor issue for not showing full base64 value.

How can i get specific value from JSON string

//main code
list ls = memberMap.get(Rz.Roles__c);
String JSONString = JSON.serialize(ls);
//Debug code
[{"attributes":{"type":"Work_Team_Member__c","url":"/services/data/v42.0/sobjects/Work_Team_Member__c/a81W00000008gIsIAI"},"Id":"a81W00000008gIsIAI","Member_Employee_ID__c":"63","Member_Name__c":"Test1","Member_Role__c":"Account Representative – General (Secondary)","Work_Team_Master__c":"a80W00000009DodIAE"}]

Read data with ILNumerics.IO.HDF5

I try ILNumerics.IO.HDF5 and can not read the following data:
Variable length strings in Datasets and Attributes.
Datasets with variable length arrays. Each cell contain a array of numbers, which are histograms.
Compound data, ie. Datasets with structs containing some numbers.
In HDFView 2.10.1 I can read this data:
https://anonfiles.com/file/13756916026cafc4e4ec7c333f235bda
How can I use ILNumerics.IO.HDF5 with this data?
I found an other post with suggestion to read string as char.
But with the variable length string an exception is thrown: "Error reading data from the attribute!"
var file = new H5File("test.h5");
H5Dataset ds1 = file.First<H5Dataset>("Wind");
var att = ds1.Attributes["Aggregator"];
var value = att.Get<char>();
Could you provide more info on how you write the string attributes and what exactly is the issue. When you say 'can not read',Do you get a null return value or do you get an exception.
I write strings as attributes in my application and it works fine. I am guessing there could be a problem in the way you write the string. As per Haymo's suggestion, I convert the string into char array and write as attribute. Here is the sample code
private ILRetArray<Char> ConvertStringToArray(string str)
{
using (ILScope.Enter())
{
ILArray<Char> A = ILMath.array<Char>(' ', 1, str.Length);
for (int i = 0; i < str.Length; i++)
{
A.SetValue(str[i], 0, i);
}
return A;
}
}
Test Case :
using (var file = new H5File("testwrite.h5"))
{
var ds = new H5Dataset("data", ILMath.rand(10,10));
file.Add(ds);
string teststr = "Test string";
ILArray<char> charStr = ConvertStringToArray(mystr);
ds.Attributes.Add(new H5Attribute("mystring",charStr));
//Read back the dataset and its attributes
var group = file.Find<H5Dataset>("data").First();
ILArray<Char> storedData = group.Attributes["mystring"].Get<Char>();
}