object de/serialization using dart - serialization

I have to serialize some WebRTC-related dart objects to send them over a signaling channel. As example I have to encode RtcSessionDescription and RtcIceCandidate instances. Both classes offer a constructor to build them in context of a given map, but no one offers a method to create such a Map out of the original object.
How can I generate strings? Do I have to make a detour over Map-objects?
As Example:
RtcSessionDescription -> Map -> String -(send_over_signalingChannel)-> String -> Map -> RtcSessionDescription

You can easily convert between Map and String using the dart:convert package.
https://www.dartlang.org/articles/json-web-service/
I don't know about RtcSessionDescription <-> Map though.
See also this question: Can I automatically serialize a Dart object to send over a Web Socket?

Finally I found a solution (using dart:convert as Günther Zöchbauer suggested):
RtcSessionDescription original = ...;
//serialize
final String serialized_sdp = JSON.encode({
'sdp':original.sdp,
'type':original.type
});
//decode
final Map sdp_map = JSON.decode(serialized_sdp);
RtcSessionDescription sdp = new RtcSessionDescription(sdp_map);

Related

problem with masstransit dynamic event publish ( json event )

we need publish multiple event as json string from DB. publish this json event by masstransit like this:
using var scope = _serviceScopeFactory.CreateScope();
var sendEndpointProvider = scope.ServiceProvider.GetService<ISendEndpointProvider>();
var endpoint = await sendEndpointProvider.GetSendEndpoint(new System.Uri("exchange:IntegrationEvents.DynamicEvent:DynamicEvent"))
var json = JsonConvert.SerializeObject(dynamicObject, Newtonsoft.Json.Formatting.None);// sample
var obj = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { });
await endpoint.Send(obj,i=>i.Serializer.ContentType.MediaType= "application/json");
and in config we use this config:
cfg.UseRawJsonSerializer();
when use this config, json event is successful published but we have strange problem : "all" event consumer is called by empty message data ! ... in Rabbitmq jsut published our "Dynamic Event", but in masstrasit all consumers called !!
Thank you for letting us know if we made a mistake
You don't need all of that JSON manipulation, just send the message object using the endpoint with the serializer configured for RawJson. I cover JSON interoperability in this video.
Also, MassTransit does not allow anonymous types to be published. You might be able to publish dynamic or Expando objects.
I used ExpandoObject like this and get this exception "Messages types must not be in the System namespace: System.Dynamic.ExpandoObject" :
dynamic dynamicObject = new ExpandoObject();
dynamicObject.Id = 1;
dynamicObject.Name = "NameForName";
await endpoint.Send(dynamicObject);
and using like this we get same result as "all consumers called":
var dynamicObject = new ExpandoObject() as IDictionary<string, object>;
dynamicObject.Add("Id", 1);
dynamicObject.Add("Name", "NameForName");
I watch your great video, you used from rabbitmq directly .. how "send the message object using the endpoint with the serializer configured for RawJson" in C# code.

Create Java 8 Stream from ArrayNode

Is it possible to create stream from com.fasterxml.jackson.databind.node.ArrayNode?
I tried:
ArrayNode files = (ArrayNode) json.get("files");
Stream<JsonNode> stream = Stream.of(files);
But it will actually give stream of one element, the initial ArrayNode object.
Correct result should be Stream<JsonNode>, can I achieve it?
ArrayNode implements Iterable. Iterable has a spliterator() method. You can create a sequential Stream from a Spliterator using
ArrayNode arrayNode = (ArrayNode) json.get("xyz");
StreamSupport.stream(arrayNode.spliterator(), false)
An ArrayNode class provides random access: you can get size() and an element by index (using get(index)). This is all you need to create a good stream:
Stream<JsonNode> nodes = IntStream.range(0, files.size()).mapToObj(files::get);
Note that this solution is better than using default spliterator (as suggested by other answerers) as it can split well and reports the size properly. Even if you don't care about parallel processing, some operations like toArray() will work more effectively as knowing the size in advance will help to allocate an array of proper size.
ArrayNode#elements returns an Iterator over it's elements you can use that to create a Stream (by leveraging StreamSupport). StreamSupport requires a Spliterator and to create a Spliterator from an Iterator you can use the Spliterators class.
ArrayNode files = (ArrayNode) json.get("files");
Stream<JsonNode> elementStream = StreamSupport.stream(Spliterators
.spliteratorUnknownSize(files.elements(),
Spliterator.ORDERED),false);
cyclops-streams has a StreamUtils class has a static method that makes this a bit cleaner (I am the author).
ArrayNode files = (ArrayNode) json.get("files");
Stream<JsonNode> elementStream = StreamUtils.stream(files.elements());
Taking into account #JB Nizet's answer that ArrayNode is an iterable with StreamUtils you can pass in the ArrayNode and get the Stream back directly.
Stream<JsonNode> elementStream = StreamUtils.stream((ArrayNode) json.get("files"));

Saxon .Net read xml from stream

all examples show how to read an xml from an local file. But how do I read a xml from a url or a stream and process it further?
Example: http://www.oreillynet.com/xml/blog/2006/03/hello_saxon_on_net_an_aspnet_i.html
thanks in advance
Look for XsltExamples.cs in the saxon-resources download available on both Sourceforge and www.saxonica.com. The very first example seems to do what you are asking for.
public static void ExampleSimple1(String sourceUri, String xsltUri) {
// Create a Processor instance.
Processor processor = new Processor();
// Load the source document
XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
// Create a transformer for the stylesheet.
XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
// Set the root node of the source document to be the initial context node
transformer.InitialContextNode = input;
// Create a serializer
Serializer serializer = new Serializer();
serializer.SetOutputWriter(Console.Out);
// Transform the source XML to System.out.
transformer.Run(serializer);
}
Are you using an XmlDocument object for reading the XML? If so, you'll want XMLDocument.Load() method, which can take a file path or URL, TextReader or Stream as input.
Likewise, XDocument.Load()(msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load(v=vs.110).aspx) has a similar set of overloads.

how to convert a a list of objects into a stream

Hi i'm building a wcf service and i'm trying to make it send the request as a StreamedResponse.Now my service used to return a list of objects and now should return just a stream.My question is how can i convert this list of objects into as stream so that it could be sent correctly.I'm writing my wcf service in C#.Thank you for your time
I recommend that you serialize your list into either JSON or XML and then turn that into a stream. Assuming your list contains strings, here is an example that serializes the list of strings into json and loads that into a memory stream. I hope this has some educational value for you and gives you a better understanding of the possibilities in this programming language :)
List<string> listOfStrings = new List<string>();
listOfStrings.Add("Hello");
listOfStrings.Add("World!");
listOfStrings.Add("Foo");
listOfStrings.Add("bar");
// this is of datatype string
var json = new JavaScriptSerializer().Serialize(listOfStrings);
// this is an array of datatype byte
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
// your stream
var memStream = new MemoryStream(bytes);
// TODO: Add code for sending your memory stream

HTTPService not properly JSON-encoding nested objects on send()

i am creating an object like this:
var myObj:Object = new Object();
myObj["someProperty"] = {
anotherProperty: "someValue",
whateverProperty: "anotherValue"
}
now i want to send it to a web server (rails):
var service:HTTPService = new HTTPService();
service.url = "http://server.com/some/path/entry.json";
service.method = URLRequestMethod.POST;
service.send( myObj );
the problem is that the server receives the json like this:
{"someProperty"=>"[object Object]"}
is this a problem with HTTPService? should i use the good old loader/urlrequest and serialize myself? by the way, serializing and then passing the string doesn't work, webserver receives empty request as GET.
but i kinda want to use the httpservice class though...
You can use a SerializationFilter with your HTTPService to correctly serialize the data you pass as an object to HTTPService.send().
The way in which this works is to create a custom SerializationFilter to perform the specific action required. In your case, you want to convert the outgoing body Object to a JSON format String. To do this you should override the serializeBody method:
package
{
import mx.rpc.http.AbstractOperation;
import mx.rpc.http.SerializationFilter;
import com.adobe.serialization.json.JSON;
public class JSONSerializationFilter extends SerializationFilter
{
override public function serializeBody(operation:AbstractOperation, obj:Object):Object
{
return JSON.encode(obj);
}
}
}
You can assign an instance of this filter to your HTTPService before calling send():
var service:HTTPService = new HTTPService();
service.url = "http://server.com/some/path/entry.json";
service.method = URLRequestMethod.POST;
//add the serialization filter
service.serializationFilter = new JSONSerializationFilter();
service.send( myObj );
Once assigned, this filter will be invoked for all the operations this HTTPService instance performs. You can also add more override methods to your custom filter to handle the incoming response.
I highly recommend using Mike Chamber's JSON serialization library for encoding / decoding (serializing) data in JSON.
Basically, you need to convert your object into a JSON representation. The JSONEncoder class is useful for this.
There's a useful (old but still very relevant for using HTTPService + JSON) tutorial that goes through it, but essentially you should call JSON.encode() on what your "someProperty" value is.
i.e.:
var dataString:String = JSON.encode(dataValue);
dataString = escape(dataString);
myObj["someProperty"] = dataString;