w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to serialize a closed immutable type with protobuf-net?
Yes. Note that many immutable types will be handled by the "auto tuple" code - if it has a constructor that accepts parameters that look just like the public members, it can infer the behaviour from that. Other than that, you can write your own DTO that has whatever layout / members you need, and add conversion operators (implicit or explicit) to and from your custom DTO and the target type (Font in this case). Your operator would have the code to get from one to the other. Then call: RuntimeTypeModel.Default.Add(typeof(Font), false) .SetSurrogate(typeof(YourCustomDTO)); The serializer will use the operators to change between the two types, and use the custom DTO on the wire. Watch out for the incoming value to the operator being null!

Categories : Misc

How to create an XDocument given an XmlWriter?
Have a look at the XContainer.CreateWriter Method: XContainer.CreateWriter Method Creates an XmlWriter that can be used to add nodes to the XContainer. Both XDocument and XElement are XContainers. Example: XDocument doc = new XDocument(); using (XmlWriter writer = doc.CreateWriter()) { // Do this directly writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteElementString("foo", "bar"); writer.WriteEndElement(); writer.WriteEndDocument(); // or anything else you want to with writer, like calling functions etc. }

Categories : C#

XDocument.Descendants() is empty even though there is content in the XDocument
I am now transferring this to an answer. There are two methods for Descendants() http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.descendants.aspx Public method Descendants() Returns a collection of the descendant elements for this document or element, in document order. (Inherited from XContainer.) Public method Descendants(XName) Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection. (Inherited from XContainer.) If you call Descendants(XName) with the wrong arguments it is highly likely you will get no descendants. If you use Descendants() [sic] I would expect to get all descendants. The reason FirstNode gives a non-e

Categories : Xml

Creating an Xdocument object from XmlNode
You can create XDocument directly from XmlNode, so you don't have to create XmlDocument instance: Dim xDoc As XDocument = XDocument.Load(New XmlNodeReader(testresults))

Categories : Xml

Serialize an object containing a child object via JSON
My Working Code Action Method [HttpPost] public JsonResult Json(AModel test) { return Json(new { Success = true }); } JQuery $.ajax({ url : "@Url.Action("Load", "MyController")", contentType : "application/json; charset=utf-8", dataType : "json", type : "POST", data : JSON.stringify({test: values}) })}).done(function (result) { //Success }).fail(function (result) { //Failed }).always(function(result) { //Always }); Models public class AModel { public string Title { get; set; } public string Text { get; set; } public BModel BModel { get; set; } } public class BModel { public string Summary { get; set; } public string Page { get; set; } } Mistakes Serialization was mising Content Ty

Categories : Asp Net Mvc

How to serialize ANY Object into a URI?
I think, solution number 4 is OK. It is simple to understand and clear. I propose similar solution in which we can use @JsonAnySetter annotation. Please, see below example: import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonProgram { public static void main(String[] args) throws Exception { C1 c1 = new C1(); c1.setProp1("a"); c1.setProp3("c"); User user = new User(); user.setName("Tom"); user.setSurname("Irg"); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.convertValue(c1, UriFormat.class)); System.out.println(mapper.convertValue(user, UriFormat.class)); } } class UriFormat { private StringBuilder build

Categories : Java

Serialize object into string
Try Class1 example = new Class1(); IFormatter formatter = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { formatter.Serialize(ms, example); ms.Position = 0; StreamReader sr = new StreamReader(ms); String text = sr.ReadToEnd(); server.Send(text); } I think that the part that got missed is resetting the position of MemoryStream to be able to read (think of it as rewinding for playback after recording)

Categories : C#

Serialize an object into SQL Server using C#
You either need to call Flush or cause sw to be Closed or Disposed in order to ensure that it's finished writing to the memStream. Also, instead of GetBuffer, you should use ToArray. GetBuffer returns an internal buffer which may be larger than the amount of bytes that have actually been written. You should also change this: catch (Exception err) { // handle the error //messageInsert = false; } to only catch specific exceptions for which you have a strategy to deal with them. And, even now, I don't think it's going to do what you wanted (which you haven't really spelled out). All that your sw.Write call does is: Writes the text representation of an object to the text string or stream by calling the ToString method on that object. If you want actual serialization to oc

Categories : C#

Can't serialize an object with Json.Net
I looked @ the code you indicated (pastebin.com/WQkP45mr) if you change the implementation of Equals method coming from IEquitable contract in the following way, it works public override bool Equals(object obj) { //if (obj == null) return base.Equals(obj); //if (!(obj is FlightSelection)) // throw new InvalidCastException("The 'obj' argument is not a FlightSelection object."); //else // return Equals(obj as FlightSelection); var flightSelection = obj as FlightSelection; if (flightSelection == null) return false; return Equals(flightSelection); } The result I obtained : {"FlightWeekSelectionType":0,"Play":1,"ProposalLineWeeks":[],"SelectedCount":0," Skip":1,"IsValidProposalLineWeeksExists":f

Categories : C#

Serialize object using GSON
if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. You can solve this problem by specifying the correct parameterized type for your generic type. Try parameterized type like List<String>. This should work

Categories : Java

Specify how to Serialize my object if it is in a list
Is there a way that I can specify that the list should be represented as a list of integers when its serialized? Yep. There are two main options: 1) Implement the ISerializable-Interface, where you can control how the object will be serialized / deserialized. OR 2) Declare your List as [NonSerialized] and also manage a private Member List, which contains your primary keys. You will have to implement the logic for loading / storing the Integer-List by your own, though. If your class to serialize is quite big, I would recommend you the second approach, because in the other case you have to manually serialize / deserialize each property.

Categories : C#

Cannot de-serialize SuperObject JSON into Object
The AV is clear - you're dereferencing a null pointer. Here you're using ctx after you have freed it. ctx := TSuperRttiContext.Create; // CREATE ctx try so := ctx.AsJson<TObj>(Ob); finally ctx.Free; // FREE ctx Ob.Free; end; Log(''); Log(so.AsJson); Log(''); Log('DE-SERIALIZING Object'); Log(''); NewOb := TObj.Create('',0,false,0); try NewOb := ctx.AsType<TObj>(SO); // USE ctx -- EXCEPTION finally ctx.Free; end;

Categories : Json

How do I XML Serialize a object without a parameter-less constructor?
Digging into some of the IL, it looks like this uses XmlSerializer - in which case, the only answer is: you can't - it demands a public parameterless constructor. You can cheat a little, though - with [Obsolete]; this works, for example: using System; using System.IO; using System.Xml.Serialization; public class Foo { public string Bar { get; set; } public Foo(string bar) { Bar = bar; } [Obsolete("You don't look like a serializer", true)] public Foo() { } } class Program { static void Main() { var ser = new XmlSerializer(typeof(Foo)); using (var ms = new MemoryStream()) { ser.Serialize(ms, new Foo("abc")); ms.Position = 0; Foo clone = (Foo)ser.Deserialize(ms); Console.Wr

Categories : Dotnet

Elegant way to serialize a MailMessage object in .NET
This will be a hack. Don't forget, MS can change it in the next versions of .Net. (With the help of ILSpy) you can write an extension method like below public static class MailExtensions { public static string ToEml(this MailMessage mail) { var stream = new MemoryStream(); var mailWriterType = mail.GetType().Assembly.GetType("System.Net.Mail.MailWriter"); var mailWriter = Activator.CreateInstance( type: mailWriterType, bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic, binder: null, args: new object[] { stream }, culture: null, activationAttributes: null); mail.GetType().I

Categories : C#

Serialize C# object, want to deserialize to an interface
JSON is what I would recommend. Of course if you want to parse it as a type, you always need to know a type, but the JSON serializer is the best for what I think you need. I would recommend using the DataContractJsonSerializer in System.Runtime.Serialization.Json as it is the most flexible in my experience. Here is some additional helpful questions/articles about emitting and deserializing to types: when does DataContractJsonSerializer include the type information? http://kashfarooq.wordpress.com/2011/01/31/creating-net-objects-from-json-using-datacontractjsonserializer/

Categories : C#

WebApi serialize object from HttpActionContext
This is what I have done when I'm dealing with cases similar to yours. Instead of creating your own Authorize attribute, you can create a MessageHandler which checks for the token and validates it on every request. This message handler is the responsible for populating the Principal in the current thread, so the Authorize attribute can work as expected allowing authorized clients to access the controller/action in question. This is how my Authorization message handler looks like: public class AuthMessageHandler : DelegatingHandler { protected ITokenProvider TokenProvider { get; private set; } protected IPrincipalProvider PrincipalProvider { get; private set; } public AuthMessageHandler(ITokenProvider tokenProvider, IPrincipalProvider principalProvider) { TokenPr

Categories : C#

Can I serialize a single object into nested XML?
As far as I can tell, your options are limited here: 1) Have your class structure reflect the XML structure and use simple framework annotations - this is the nested class member structure you already mentioned a distaste for. 2) Implement IXmlSerializable and do custom serialization. This is custom serialization, after all.

Categories : C#

How to serialize and deserialize a CipherInputStream object
Probably U wouldn't have implemented serialiazable marker class . Suppose class A is the one U need to serialize , then : class A implements serializable { //class variables and methods }

Categories : Java

Error: Object reference not set to an instance of an object./The connection was not closed. The connection's current state is open
For the first error, your executeScalar() call is returning a null value. Either refine your query - you can check your query by running it directly in your database - or change your logic to deal with null values. For the second error, if calling Open() is throwing that error, it's because the connection object was in use before and was not closed properly. It's usually considered bad practice to reuse connections like that, so consider creating a new connection instance when you go opening one. Edit: I tried to imply something in the second paragraph there, but now I feel I must make it explicit: don't forget to deal with the connection you left open there, as it may be a major performance hog for your application. Specially since it's an ASP.NET one. Dispose of connections as soon as

Categories : C#

How to create DVD Video with closed captioning?
http://latentimagedesign.com/ClosedCaptionCreator/create.php You can load your srt file and export as an adobe XML file. Use adobe CC to convert the XML file to SCC for DVD authoring or embed the closed caption file.

Categories : Misc

How to construct object to serialize like elements under the same parent
Assuming you mean that you want <Vehicles> <Vehicle> <Type color="red" speed="50mph">Ford</Type> </Vehicle> <Vehicle> <Type color="blue" speed="70mph">Toyota</Type> </Vehicle> </Vehicles> you almost have it see MSDN [XmlArray("Vehicles")] public List<Vehicle> Vehicles { get; set; }

Categories : C#

serialize object as null based on one of its properties
What's wrong with this approach? public static JsonSerializerSettings MySettings() { return new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), TypeNameHandling = TypeNameHandling.All, DefaultValueHandling = DefaultValueHandling.Ignore, DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind, }; } In your PriceConverter: if (0 == price.Amount) { writer.WriteNull(); return; } else { writer.WriteRaw(JsonConvert.SerializeObject(value, Somewhere.MySettings())); return; } And in your program: public static void Custom(Price p) { var settings = Somewhere.MySettings(); settings.Converters = new List<JsonConverter> { new PriceConverter() }; C

Categories : Dotnet

Restsharp serialize complex object for json
Based on the fact that you're setting request.RequestFormat = DataFormat.Json; I'm assuming you want to project object as JSON in the body of the request. To do this, you would use request.AddBody(project); rather than request.AddObject(project); I've never used AddObject(), but if I understand the source comments correctly, it's adding the properties of the object to your request as form parameters.

Categories : C#

Deep cloning an object : Clone vs Serialize
Trick here is that you must unset duplicate entity id. Otherwise breaks the logic of the doctrine. Doctrine has some known limitations. Also check this question, its very similar.

Categories : PHP

Visual Studio how to serialize object from debugger
It might be possible to use the intermediate window to serialize it and then copy the content to your favorite editor. Another option is to override the ToString() method and call it while in debug mode. You can also write the contents out to a file shortly before the crash, or wrap the code into a try/catch and write the file then. I'm assuming you can identify when it's crashing.

Categories : C#

How to serialize - deserialize params hash object?
Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. class User < ActiveRecord::Base serialize :preferences end user = User.create(preferences: {background: "black", display: "large"}) User.find(user.id).preferences # => {background: "black", display: "large"}

Categories : Ruby On Rails

Serialize object property with JMSSerializerBundle on entity
Its a well-known bug of jms serializer. You can store data in database as array and serialize later as array.

Categories : Json

Unable to serialize custom object activeandroid
You also need to extent Contact from Model: @Table(name = "contact") public class Contact extends Model{ @Column(name = "id") private String id; @Column(name = "name") private String name; @Column(name = "number") private String number; } Now everything should work out of the box. It's a bit late for a response but perhaps I will help someone else.

Categories : Sqlite

Serialize form data into JSON object
This is the code that gets you the specified JSON: $(function() { $('form').on('click', 'button', function() { var clientId = $('form').find('input[name="client_id"]').val(), $tables = $('form').find('table'), data = {}; data.client_id = clientId; data.carts = []; $.each($tables, function(i, v) { var cart = {}; cart.cart_id = $(v).attr('id'); cart.items = []; $rows = $(v).find('tr'); $.each($rows, function(i, v) { var item = {}; item.code = $(v).find('input[name="code"]').val(); item.description = $(v).find('input[name="description"]').val(); cart.items.push(item); }); data.carts.push(ca

Categories : Javascript

Can I automatically serialize a Dart object to send over a Web Socket?
You will need to serialize the Dart object somehow. You can try JSON, or you can try the heavy-duty serialization package. There is no fully automatic JSON serialization for custom Dart classes. You will need to add a custom toJson serializer and create some sort of fromJson constructor. e.g. if you had a Person class, you could do something like this: import 'dart:json' as json; class Person { String name; int age; Person(this.name, this.age); Person.fromJson(String json) { Map data = json.parse(json); name = data['name']; age = data['age']; } Map toJson() { return {'name': name, 'age': age}; } } Note: the fromJson is just a convention. You will need to call it somehow, there is no built-in mechanism to take an arbitrary JSON string and call the righ

Categories : HTML

How to serialize a complex object and save into file for latter user in c#
If you need to use XmlSerializer, one option is XmlAttributeOverrides - this is quite fiddly to use, but allows you to specify how it should be serialized at runtime rather than at compile-time. You do need to cache and re-use the serializer instance, though - otherwise you will leak memory (an entire assembly per serializer instance). However, a much better option might be (and this is my usual guidance whenever serialization gets remotely tricky): create a separate set of types for serialization - a "DTO layer", if you will. These DTO types should: be simple (data only, no real logic) be structured in the way the serializer wants to work contain any metadata etc that the serializer is interested in have some kind of mapping to/from your actual entity types Then rather than trying to

Categories : Dotnet

Is it possible to deserialize and serialize json object in different propety names?
[JsonProperty(propertyName: "address")] is making it serialise as "address". Remove the attribute and it'll serialise to the C# Property name. string json = Newtonsoft.Json.JsonConvert.SerializeObject(Class);

Categories : C#

How to handle special characters like  when Serialize/Deserialize xml object?
I don't have a solution for your question, but here is the background info. The string &#2; is XML for saying the character with value of '2'. According to XML 1.0 this is not a valid character. See http://www.w3.org/TR/2004/REC-xml-20040204/#NT-Char. The .Net CLR is consistent. The Xml serialiser will happily generated XML documents with illegal character. However the deserialiser will throw when an illegal character is encountered. See http://msdn.microsoft.com/en-us/library/aa302290.aspx for more details. XML 1.1 relaxes the restriction. But .Net only support XML 1.0.

Categories : C#

Serialize and deserialize Object with non standard constructor - protobuf-net
I would try protobuf-net. Take a look here: http://code.google.com/p/protobuf-net/ Quote from Website: protocol buffers is the name of the binary serialization format used by Google for much of their data communications. It is designed to be: small in size - efficient data storage (far smaller than xml) cheap to process - both at the client and server platform independent - portable between different programming architectures extensible - to add new data to old messages

Categories : C#

parse/serialize complex json object with GSON
You will need lets say class A with one instance of class B in it. public class A { private B response; } then you will need class B to have 1 instance of class C public class B { private C request_types; } Then C would contains int c_id and array of a class D and a class for each of the other arrays as well. Then class D would contain a single object for class E called objectKey. Class E would contains all the fields under objectKey... So on and so forth... you're right the JSON is crazy convoluted.

Categories : Android

How to serialize scala object with multiple-arg constructor using Jackson?
Quoting from scala.annotation.meta: By default, annotations on (val-, var- or plain) constructor parameters end up on the parameter, not on any other entity. Annotations on fields by default only end up on the field. The meta-annotations in package scala.annotation.meta are used to control where annotations on fields and class parameters are copied. This is done by annotating either the annotation type or the annotation class with one or several of the meta-annotations in this package. So the annotation goes to the constructor parameter. You need to assign it to the getter as well as the constructor parameter: class MyClass @JsonCreator() (@(JsonProperty @getter @param) val arg: String)

Categories : Json

How to serialize an object to XML that can be stored SQL database field of type XML
You can use StringWriter with XmlWriter to produce the xml string then save to your database string xmlResult = string.Empty; var xmlSerializer = new XmlSerializer(typeof(car)); using (var stringWriter = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(stringWriter)) { xmlSerializer.Serialize(xmlWriter, car); } xmlResult = stringWriter.ToString(); } // save xmlResult to DB

Categories : C#

How to (De)serialize field from object based on annotation using Jackson?
Most (all?) of your requirements can be accomplished through the use of a contextual serializer. Taking one answer from ContextualDeserializer for mapping JSON to different types of maps with Jackson and Jackson's wiki (http://wiki.fasterxml.com/JacksonFeatureContextualHandlers) I was able to come up with the following. You need to start with the @JsonId annotation, which is the key indicating a property needs to only use the Id property. import com.fasterxml.jackson.annotation.*; import java.lang.annotation.*; @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation // important so that it will get included! public @interface JsonId { } Next is the actual ContextualSerializer, which does the heavy lifting. import com.

Categories : Java

JSON serialize a custom C# struct to a string, not an Object
What I have done for now, is add a second property on the parent CustomClass class... public string MyCustomStructValue { get { return MyCustomStruct.ToString(); } } then add the [IgnoreDataMember] attribute to the original property... [IgnoreDataMember] public CustomStruct MyCustomStruct { get; set; } which works fine with the following action: public IEnumerable<CustomClass> Get() { return GetResults(); }

Categories : C#

Serialize java class with custom object attributes
Actually it is not necessary to wrap float[] and HashMap<String,float> as they themselves are serializable. Another thing is that if MyClass1 and MyClass2 are serializable than you can use @Lob. According to this wikibook, By default in JPA any Serializable attribute that is not a relationship or a basic type (String, Number, temporal, primitive), will be serialized to a BLOB field. In that wikibook, there is also an example using @Lob for the class Image. @Entity public class Employee { ... @Basic(fetch=FetchType.LAZY) @Lob private Image picture; ... } Hope this might help you.

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.