Kotlin convert String to Iterable - kotlin

I have an iterable of People that I save as a string after converting from json. I want to know how would I convert the string back to a list.
// Save data
val peopleString = myList.toString()
// String saved is
[People(name=john, age=23), People(name=mary, age=21), People(name=george, age=11)]
Now is it possible to convert peopleString back to a list?
val peopleList: List<People> = peopleString.?

In short, no... kind of.
Your output is not JSON, and toString() is the wrong function to use if you wanted JSON. The output of toString() is not a proper serialization format that can be understood and used to rebuild the original data structure.
Converting a data structure into some format so that it can be transmitted and later rebuilt is known as serialization. Kotlin has a serializer which can serialize objects into a number of different formats, including JSON: https://github.com/Kotlin/kotlinx.serialization#quick-example.
It's not as easy to use as toString(), but that's to be expected as toStrings's purpose is very different from serialization.

Related

how can I serialize tuples as list in F#?

I have a library that sends me results that include tuples. I need to process some of the data, serialize it and then it goes on its way to another system.
the tuples are ALWAYS made of 2 values but they are extremely wasteful when serialized:
(3, 4)
will serialize as:
{"Item1":3,"Item2":4}
whereas
[3; 4]
will serialize as:
[3,4]
I would like to avoid rebuilding the whole data structure and copying all the data to change this part.
Is there a way, at the serializer level, to convert the tuples into list?
the next process' parser can be easily changed to accommodate a list instead of tuples, so it seems like the best scenario.
the ugly option would be to fix the serialized string with a regex, but I would really like to avoid doing this.
You can override the default serialization behaviour by specifying your own JsonConverter. The following example shows a formatter that writes int * int tuples as two-element JSON arrays.
open Newtonsoft.Json
type IntIntConverter() =
inherit JsonConverter<int * int>()
override x.WriteJson(writer:JsonWriter, (a:int,b:int), serializer:JsonSerializer) =
writer.WriteStartArray()
writer.WriteValue(a)
writer.WriteValue(b)
writer.WriteEndArray()
override x.ReadJson(reader, objectType, existingValue, hasExistingValue, serializer) =
(0, 0)
let sample = [ (1,2); (3,4) ]
let json = JsonConvert.SerializeObject(sample, Formatting.None, IntIntConverter())
The result of running this will be [[1,2],[3,4]]. Note that I have not implemented the ReadJson method, so you cannot yet parse the tuples. This will involve some extra work, but you can look at existing JsonConverters to see how this should be done.
Also note that this is for a specific tuple type containing two integers. If you need to support other tuples, you will probably need to provide several variants of the converter.

Spring Mongo convert to document from json string

I have a Mongo collection annotated with #Document and I want the possibility to also get that Java object from a String (JSON) as we're getting these classes pushed into a queue as String.
Is there a method in Spring-Data-Mongo which converts from JSON to the actual Document object?
#Autowired
MongoTemplate mongoTemplate;
and then
mongoTemplate.getConverter().read(MatchMongo.class, (DBObject) JSON.parse(json));
Thanks to freakman, your answer helped a lot
You can try com.mongodb.util.JSON.parse() method. It returns object so you probably have to do the casting + it may be it need "class" field inside json string.

Protobuf concatenation of serialized messages into one file

I have some serialization in google protobuf in a series of files, but wonder if there is a shortcut way of concatenating these smaller files into one larger protobuf without worrying about reading each and every protobuf and then grouping these objects and outputting.
Is there a cheap way to join files together? I.e. do I have serialize each individual file?
You can combine protocol buffers messages by simple concatenation. It appears that you want the result to form an array, so you'll need to serialize each individual file as an array itself:
message MyItem {
...
}
message MyCollection {
repeated MyItem items = 1;
}
Now if you serialize each file as a MyCollection and then concatenate them (just put the raw binary data together), the resulting file can be read as a one large collection itself.
In addition to jpas answer, it might be relevant to say that the data does not need to be in the exact same container, when being serialized, for it being compatible on deserialisation.
Consider the following messages:
message FileData{
required uint32 versionNumber = 1;
repeated Data initialData = 2;
}
message MoreData{
repeated Data data = 2;
}
It is possible to serialize those different messages into one single data container and deserialize it as one single FileData message, as long as the FileData is serialized before zero or more MoreData and both, the FileData and MoreData have the same index for the repeated field.

JSON Deserialize Error

I wanna pass the json to server, below is the json format:
[{"StaffID":"S01","StaffRank":"Manager"},{"StaffID":"S02","StaffRank":"Waiter"}]
After I tried the following code to get the json array:
Dim request As String = New StreamReader(data).ReadToEnd
response = AddStaff(JsonConvert.DeserializeObject(Of tbl_Staff)(request))
Return JsonConvert.SerializeObject(response)
I get the new error which is:
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'tbl_Staff' because the type requires a JSON object
(e.g.{"name":"value"}) to deserialize correctly. To fix this error
either change the JSON to a JSON object (e.g. {"name":"value"}) or
change the deserialized type to an array or a type that implements a
collection interface (e.g. ICollection, IList) like List that can
be deserialized from a JSON array. JsonArrayAttribute can also be
added to the type to force it to deserialize from a JSON array."
What is the problem? Thanks
The problem is you cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'tbl_Staff' because the type requires a JSON object (e.g.{"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
It seems like no matter how detailed I make that error message, people just don't read it :-\
I found the answer.I just change the code to List. Then working perfectly.
Dim request As String = New StreamReader(data).ReadToEnd
response = AddStaff(JsonConvert.DeserializeObject(Of List(Of tbl_Staff))(request))
Return JsonConvert.SerializeObject(response)

asp.net WCF and JSON

I know returning types in a wcv service is allowed, and it will convert the object to json. But what if I don't want to return a random type, but return a string with formatted json? I can construct json my self but it can a) be messy, and b) not auto encode html values.
How do I do build a custom formatted json string? Off the top of my had, can I return a dictionary with key, value pairs? Will the value be encoded so you can transmitted without running the risk of malformed json?
Have a look at JSON.Net. I've used it in the past for serializing/deserializing to/from Json. It also (according to the web page) has support for converting Json to/from XML, so it seems reasonable that there would be some functions in there to build arbitrary Json strings in a way that is less error-prone than doing it yourself.
You can specify a return type of object and then use an anonymous type to return an arbitrary object. If you want to return an arbitrary collection, you can return IEnumerable, and use that to return a collection of anonymous types.
as far as I can understand, you want a webservice that returns a string that can be parsed using json (like JSON.parse(yourReturnedString)... As ckramer answered, JSON.NET can help to format your whatever dictionary into json but you should know dictionary is "json-serialised" as key:'your key', value:'your value§that can be also an object that will be serialized', so if you are using JSON.NET, you should also once it has been deserialezed, remove all the "key": and ,"value" JSON.NET returned.
so good so far you should definetely declare your webmethod as a method that returns a JSON format.
hope you found a solution before this answer...