Escritor JSON: ¿reemplazar por xmlwriter?

Without having spent a lot of time on this subject, I'm curious what might be the most straightforward way to allow my existing code to serialize to json in addition to xml. The existing code uses a xmlwriter to perform some sophisticated serialization for a specific purpose, so ultimately I'd like to be able to pass a jsonserializer in place of the xml one and have it produce json instead of xml.

Do any of the json libs handle something like this?

preguntado el 14 de enero de 13 a las 06:01

2 Respuestas

No, there's no direct drop-in replacement. The APIs for existing JSON serializers is much different. They need to have the entire model in memory and serialize it in one step. For example with JSON.NET usarías:

string json = JsonConvert.SerializeObject(product);

The correct way to achieve what you are looking for is to abstract the actual serialization of the object behind an interface:

public interface IMySerializer
{
    void Serialize(MyObject instance, Stream stream);
}

Now you could have multiple implementations of this interface such as MySerializerXml, MySerializerJson, MySerializerCsv...

Now the code that depends on the serialization would simply work with an IMySerializer. So when you need to handle a new format all you have to do is entrar un momento an implementation of this interface.

Respondido el 14 de enero de 13 a las 06:01

There is no direct replacement for an XmlWriter. If you want to support both XML and JSON, I would suggest serialising via data-contracts, i.e. use attributes on your data objects to indicate the desired serialised format. Take a look at DataContractJsonSerializer for JSON and DataCOntractSerializer for XML.

Your model objects would look something like this:

[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person
{
    [DataMember()]
    public string FirstName;
    [DataMember]
    public string LastName;
    [DataMember()]
    public int ID;
}

Respondido el 14 de enero de 13 a las 06:01

i have very specific logic in this case, which serializes differently based on state and some other logic, thus it must be manually serialized by walking my object tree and writing via an xml (or other) writer. So I'm looking for a way to abstract the writer in some way where i could substitute others. - brady moritz

You could apply your specific logic and use that to generate a set of classes which maps directly to your JSON / XML structure. - Colina

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.