Search Results

Search found 468 results on 19 pages for 'deserialize'.

Page 12/19 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Faster way to clone.

    - by AngryHacker
    I am trying to optimize a piece of code that clones an object: #region ICloneable public object Clone() { MemoryStream buffer = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(buffer, this); // takes 3.2 seconds buffer.Position = 0; return formatter.Deserialize(buffer); // takes 2.1 seconds } #endregion Pretty standard stuff. The problem is that the object is pretty beefy and it takes 5.4 seconds (according ANTS Profiler - I am sure there is the profiler overhead, but still). Is there a better and faster way to clone?

    Read the article

  • Protocol buffer deserialization and a dynamically loaded DLL in Compact Framework

    - by cloudraven
    I saw a question related to this on the full framework here. Since it seems to have stayed unresolved for quite a while and this is for the compact framework, I though it would be better to create a new question for it. I want to deserialize types for which I am loading assemblies dynamically (with Assembly.LoadFrom) and I am getting a "Unable to identify known-type for ProtoIncludeAttribute" error. In the related question I mentioned, it was hinted that hooking AppDomain.AssemblyResolve event would help solving the problem. It makes sense for the full framework, but that event is not available in the CF. I wonder if there is a way to do this with CF. The structures I am using look a lot like this and all the classes required for deserialization are loaded from the same Assembly. If the assembly is referenced instead of dynamically loaded it works fine, but fails if done dynamically.

    Read the article

  • XDocument default namespace

    - by Anthony Faull
    How can I set the default namespace of an existing XDocument (so I can deserialize it with DataContractSerializer). I tried the following: var doc = XDocument.Parse("<widget/>"); var attrib = new XAttribute("xmlns", "http://schemas.datacontract.org/2004/07/Widgets"); doc.Root.Add(attrib); The exception I get is is The prefix '' cannot be redefined from '' to 'http://schemas.datacontract.org/2004/07/Widgets' within the same start element tag. Any ideas?

    Read the article

  • Hibernate session method to update object

    - by EugeneP
    I need this roadmap of a Hibernate managed object instance. First, I create an instance with initial properties and persist this object in a db. Then session associated with this object is closed. But still, I serialize my object and on the next step deserialize it, invoke some setters, and again, I need to update what changed in a database. What methods of Hibernate session should I use? persist() or save() on the first step and saveOrUpdate() on the second? In fact I see that saveOrUpdate() can be used on each step. What would you recommend?

    Read the article

  • Unknown attribute xsi:type in XmlSerializer

    - by vanccoon
    I am learning XML Serialization and meet an issue, I have two claess [System.Xml.Serialization.XmlInclude(typeof(SubClass))] public class BaseClass { } public class SubClass : BaseClass { } I am trying to serialize a SubClass object into XML file, I use blow code XmlSerializer xs = new XmlSerializer(typeof(Base)); xs.Serialize(fs, SubClassObject); I noticed Serialization succeed, but the XML file is kind of like ... If I use XmlSerializer xs = new XmlSerializer(typeof(Base)); SubClassObject = xs.Deserialize(fs) as SubClass; I noticed it will complain xsi:type is unknown attribute(I registered an event), although all information embedded in the XML was parsed successfully and members in SubClassObject was restored correctly. Anyone has any idea why there is error in parsing xsi:type and anything I did wrong? Thanks

    Read the article

  • Json problem with Page Method call on IE 8.

    - by ProfK
    I have the following code that populates a select element with values from an ajax call, via a Page Method. In FF, the code works perfectly, in IE8 I get the error: 'ResourceList[...].id' is null or not an object. What can I look at here? function readShift(jsonString) { var shiftInfo = Sys.Serialization.JavaScriptSerializer.deserialize(jsonString); var listItems = ""; listItems += "<option value='0'>[Unassigned]</option>"; for (var i = 0; i < shiftInfo.ResourceList.length; i++) { listItems += "<option value='" + shiftInfo.ResourceList[i].id + "'>" + shiftInfo.ResourceList[i].name + "</option>"; } $("#" + resourceListId).html(listItems); };

    Read the article

  • Collectable<T> serialization, Root Namespaces on T in .xml files.

    - by Stacey
    I have a Repository Class with the following method... public T Single<T>(Predicate<T> expression) { using (var list = (Models.Collectable<T>)System.Xml.Serializer.Deserialize(typeof(Models.Collectable<T>), FileName)) { return list.Find(expression); } } Where Collectable is defined.. [Serializable] public class Collectable<T> : List<T>, IDisposable { public Collectable() { } public void Dispose() { } } And an Item that uses it is defined.. [Serializable] [System.Xml.Serialization.XmlRoot("Titles")] public partial class Titles : Collectable<Title> { } The problem is when I call the method, it expects "Collectable" to be the XmlRoot, but the XmlRoot is "Titles" (all of object Title). I have several classes that are collected in .xml files like this, but it seems pointless to rewrite the basic methods for loading each up when the generic accessors do it - but how can I enforce the proper root name for each file without hard coding methods for each one? The [System.Xml.Serialization.XmlRoot] seems to be ignored.

    Read the article

  • Can anyone recommend a .Net XML Serialization library?

    - by James
    Can anyone recommend a .Net XML Serialization library (ideally open source). I am looking for a robust XML serialization library that I can throw any object at, which will produce a human readable XML representation of the public properties for logging purposes. I never need to be able to deserialize. XmlSerializer's requirement of an object having a parameter constructor is too restrictive for what I want. DataContractSerializer does not give enough control over the output (which is not particularly human-readable). Any recommendations appreciated! Thanks

    Read the article

  • Post serialized to xml object to mvc action

    - by Maxim
    Hello! i have 2 projects. First project send to 2-nd via http-post requests, as serialized to XML class instances. Ex: <?xml version="1.0" encoding="utf-16"?> <MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <UserId>test user</UserId> ... How can i recieve it in action of 2-nd project? [HttpPost] public ActionResult Index(MyObject id) { ... or like string, and deserialize after? Thanx.

    Read the article

  • Asp.Net Error Message:Unable to validate data

    - by Amitabh
    We have a Asp.Net Webform page which contains a GridView inside UpdatePanel and refreshes every minute. And every one minute we get the following error in Event log. Error Message:Unable to validate data. Stack Trace: at System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString). We have tried the following. Adding a static machine key in the Web.Config. (Did not work?) Disabling the View State Mac in the Web,.Config using following entry. (Did not work) <pages buffer="true" enableViewStateMac="false"> Is there something else that might cause this?

    Read the article

  • Custom ArrayList serialization

    - by rayman
    Hi, i was trying to serialize an ArrayList which contacins custom objects. I`am serializing it in a servlet(server side), and deserialize at the client side. (using ObjectOutputStream,ObjectInputStream) it worked fine, when I work with ArrayList< String but when i tried it with ArrayList< MyObject i couldnt get any results in the client side, this is the exception: java.lang.ClassNotFoundException: web.MyObject *ofcourse that i have done this: MyObject implements Serializable ... MyObject contains only String fields in it. what have I done worng? Thanks, ray.

    Read the article

  • How to serialize a data of type string without using StringWriter as input

    - by starz26
    I want to serialize a input data of type string, but do not want to use StringWriter and StringReader for for serializing/Deserializing. The reason for this is when a escapse chars are sent as part of the Input string for serializing, it is serialized but some Spl chars are inserted in the xml(eg:"").I'm getting an XMl error while deserializing this serialized data. void M1() { string str = 23 + "AC"+(char)1; StringWriter sw = new StringWriter(); XmlSerializer serializer = new XmlSerializer(typeof(String)); serializer.Serialize(sw, str); System.Console.WriteLine("String encoded to XML = \n{0} \n", sw.ToString()); StringReader sr = new StringReader(sw.ToString()); String s2 = (String)serializer.Deserialize(sr); System.Console.WriteLine("String decoded from XML = \n {0}", s2); }

    Read the article

  • Fetching JSON object from Servlet Java

    - by ChrisA
    I want to create an application that will fetch a JSON object from a servlet to deserialize it, and then use its variables to do other things. My servlet has the following code in the doPost: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ObjectOutputStream os; os = new ObjectOutputStream(response.getOutputStream()); String s = new String("A String"); Gson gson = new Gson(); String gsonObject= gson.toJson(s); os.writeObject(gsonObject); os.close(); } Now, while the servlet is running, I can access it via a browser, if I post same code in the doGet method, that would download a servlet file, which is not what I want. What should I use in my second application that would connect to the servlet, fetch the object, so that I can manipulate it later? Thanks in advance.

    Read the article

  • Should GSON ignore varying types if they're not used in a class?

    - by loeschg
    I'm making an API call that returns JSON which has a particular field which either returns false or a map depending on content. It's a field that I don't care about. I expected GSON to ignore this particular field, though it doesn't seem to be. The object generation fails with the following message: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 403560 I've seen this particular question (Gson deserialize json with varying value types). I want to make sure I need to make a custom deserializer before doing so. I'm wondering if I may have another issue. edit: Example: "anonymous_flag": { } vs "anonymous_flag": "yes" Another Edit: I actually had the field in my model object... I was referencing the wrong class. Judge away :)

    Read the article

  • How to create and restore a backup from SqlAlchemy?

    - by swilliams
    I'm writing a Pylons app, and am trying to create a simple backup system where every table is serialized and tarred up into a single file for an administrator to download, and use to restore the app should something bad happen. I can serialize my table data just fine using the SqlAlchemy serializer, and I can deserialize it fine as well, but I can't figure out how to commit those changes back to the database. In order to serialize my data I am doing this: from myproject.model.meta import Session from sqlalchemy.ext.serializer import loads, dumps q = Session.query(MyTable) serialized_data = dumps(q.all()) In order to test things out, I go ahead and truncation MyTable, and then attempt to restore using serialized_data: from myproject.model import meta restore_q = loads(serialized_data, meta.metadata, Session) This doesn't seem to do anything... I've tried calling a Session.commit after the fact, individually walking through all the objects in restore_q and adding them, but nothing seems to work. What am I missing? Or is there a better way to do what I'm aiming for? I don't want to shell out and directly touch the database, since SqlAlchemy supports different database engines.

    Read the article

  • Json Object to a Multidimensional C# Array?

    - by Nick Brooks
    Is there a way to convert a Json Object to a Multidimensional C# Array? I know it might be impractical but I can't be bothered to write classes and then deserialize the strings into them. List<string> ohyeah = (List<string>)JsonConvert.DeserializeObject(g.CommToken); That returns an Invalid Cast exception! Example: {"method":"getCommunicationToken","header":{"uuid":"9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7","clientRevision":"20100323.02","session":"c0d3e8b5d661f74c68ad72af17aeb5a1","client":"gslite"},"parameters":{"secretKey":"d9b687fa10c927f102cde9c085f9377f"}} I need to get something like that : j["method"]; //This will equal to getCommunicationToken j["header"]["uuid"]; //This will equal to 9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7 I literally need to parse the json object into an array.

    Read the article

  • Which Java library lets me initialize an object's properties from a properties file?

    - by Kjetil Ødegaard
    Is there a Java library that lets you "deserialize" a properties file directly into an object instance? Example: say you have a file called init.properties: username=fisk password=frosk and a Java class with some properties: class Connection { private String username; private String password; public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } } I want to do this: Connection c = MagicConfigurator.configure("init.properties", new Connection()) and have MagicConfigurator apply all the values from the properties file to the Connection instance. Is there a library with a class like this?

    Read the article

  • WCF client hangs on response

    - by JohnIdol
    I have a WCF client (running on Win7) pointing to a WebSphere service. All is good from a test harness (a little test fixture outside my web app) but when my calls to the service originate from my web project one of the calls is extremely slow to deserialize (it takes up to 10 times longer) and not just the first time. I can see from fiddler that the response comes back quickly but then the WCF client hangs on the response itself for more than a minute before the next line of code is hit by the debugger, almost if the client was having trouble deserializing. This happens only if in the response I have a given pdf string, base64 encoded chunked. If for example the service raises a fault (this pdf string is not there) then the response is deserialized immediately. Again, If I send the exact same envelope through Soap-UI or from outside the web project all is good. I am at loss - What should I be looking for and is there some config setting that might do the trick? Any help appreciated!

    Read the article

  • Scala loop returns as Unit and compiler points to "for" syntax?

    - by DeLongey
    Seems like Unit is the theme of my troubles today. I'm porting a JSON deserializer that uses Gson and when it comes to this for loop: def deserialize(json:JsonElement, typeOfT:Type, context:JsonDeserializationContext) = { var eventData = new EventData(null, null) var jsonObject = json.getAsJsonObject for(entry <- jsonObject.entrySet()) { var key = entry.getKey() var element = entry.getValue() element if("previous_attributes".equals(key)) { var previousAttributes = new scala.collection.mutable.HashMap[String, Object]() populateMapFromJSONObject(previousAttributes, element.getAsJsonObject()) eventData.setPreviousAttributes(previousAttributes) eventData } else if ("object".equals(key)) { val `type` = element.getAsJsonObject().get("object").getAsString() var cl = objectMap.get(`type`).asInstanceOf[StripeObject] var `object` = abstractObject.retrieve(cl, key) eventData.setObject(`object`) eventData } } } The compiler spits out the error type mismatch; found : Unit required: com.stripe.EventData and it points to this line here: for(entry <- jsonObject.entrySet()) Questions Confirm that it is indeed the Gson method entrySet() appearing as unit? If not, what part of the code is creating the issue? I've set return types/values for eventData class methods Is there a workaround for the Gson Unit issue? Thanks!

    Read the article

  • Deserializing only select properties of an Entity using JDOQL query string?

    - by user246114
    Hi, I have a rather large class stored in the datastore, for example a User class with lots of fields (I'm using java, omitting all decorations below example for clarity): @PersistenceCapable class User { private String username; private String city; private String state; private String country; private String favColor; } For some user queries, I only need the favColor property, but right now I'm doing this: SELECT FROM " + User.class.getName() + " WHERE username == 'bob' which should deserialize all of the entity properties. Is it possible to do something instead like: SELECT username, favColor FROM " + User.class.getName() + " WHERE username == 'bob' and then in this case, all of the returned User instances will only spend time deserializing the username and favColor properties, and not the city/state/country properties? If so, then I suppose all the other properties will be null (in the case of objects) or 0 for int/long/float? Thank you

    Read the article

  • jquery ajax calls with scope safety

    - by acidzombie24
    My gut tells me that if i am on a laggy server and the user fires two events fast enough on the success function c will be the value of the most recent event causing func1 to use the wrong value. <--- This is a guess, i haven't proved it. Its a feeling. How do i ensure that i use the right value when calling func1? I prefer not to send c to the server and i dont know if or how to serialize the data and deserialize it back. How do i make this code safe? $('.blah').click(function (event) { var c = $(this).closest('.comment'); ... $.ajax({ url: "/u", type: "POST", dataType: "json", data: { ... }, success: function (data) { func1(c. data.blah);//here

    Read the article

  • Why can't I register a custom model binder for a List<int>?

    - by quarksoup
    I have an action that looks like public ActionResult GetUsers(List<int> userIds) {//do stuff} The list of userIds can become quite long, so I want to use Json.Net to deserialize it. To do so I created an IModelBinder implementation, which works fine for other objects, but never gets called for a List. The IModelBind looks like this public class JsonBinder : System.Web.Mvc.IModelBinder { public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext) { //Do model binding stuff using Json.Net } } And I register this model binder with this line ModelBinders.Binders.Add(typeof(List<int>), new JsonBinder()); However the JsonBinder is never called. Why is this? Should I be using a ValueProvider?

    Read the article

  • Rails: What's the suggested approach to retrieve xml from an outside source

    - by Syrahn
    Rails newbie (though long time programmer) here. I'm writing an test app that retrieves data from several outside sources (think Twitter, RSS feeds, etc.) and under certain circumstances, it stores that data in a db (or presents it to the user). The data model and the views are trivial. What I'm having difficulty with is making the actual xml HTTP call to the outside source and deserialize the xml response so I can query/use it in my controller/helper. What library/gem should I use to accomplish this? I tried looking this up around the net, but only came up with some article from 2006 which, knowing how fast Rails has developed, might well be completely deprecated. Your help is much appreciated.

    Read the article

  • I have a custom type which i want to serialize, this custom type accepts input which might consists

    - by starz26
    I have a custom type which i want to serialize, this custom type accepts input which might consists of escape chars. M1_Serilizer(MyCustomType customTypeObj) {XmlSerializer serializer = new XmlSerializer(typeof(MyCustomType)); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); serializer.Serialize(sw, customTypeObj); string str= sw.ToString(); M2_Deserializer(str); } M2_Deserializer(string str) { XmlSerializer serializer = new XmlSerializer(typeof(MyCustomType)); StringReader sr = new StringReader(str); MyCustomType customTypeObj = (MyCustomType)serializer.Deserialize(sr); } when escape type chars are part of the CustomTypeObj, on deserialization it throws an exception. Q1)How do i overcome this?, Q2)I should use StringReader and StringWriter and not memorystream or other thing ways. StringWriter/reader will only serve my internal functionality Q3)How can these escape chars be handled?

    Read the article

  • Dynamically loading Assemblies to reduce Runtime Depencies

    - by Rick Strahl
    I've been working on a request to the West Wind Application Configuration library to add JSON support. The config library is a very easy to use code-first approach to configuration: You create a class that holds the configuration data that inherits from a base configuration class, and then assign a persistence provider at runtime that determines where and how the configuration data is store. Currently the library supports .NET Configuration stores (web.config/app.config), XML files, SQL records and string storage.About once a week somebody asks me about JSON support and I've deflected this question for the longest time because frankly I think that JSON as a configuration store doesn't really buy a heck of a lot over XML. Both formats require the user to perform some fixup of the plain configuration data - in XML into XML tags, with JSON using JSON delimiters for properties and property formatting rules. Sure JSON is a little less verbose and maybe a little easier to read if you have hierarchical data, but overall the differences are pretty minor in my opinion. And yet - the requests keep rolling in.Hard Link Issues in a Component LibraryAnother reason I've been hesitant is that I really didn't want to pull in a dependency on an external JSON library - in this case JSON.NET - into the core library. If you're not using JSON.NET elsewhere I don't want a user to have to require a hard dependency on JSON.NET unless they want to use the JSON feature. JSON.NET is also sensitive to versions and doesn't play nice with multiple versions when hard linked. For example, when you have a reference to V4.4 in your project but the host application has a reference to version 4.5 you can run into assembly load problems. NuGet's Update-Package can solve some of this *if* you can recompile, but that's not ideal for a component that's supposed to be just plug and play. This is no criticism of JSON.NET - this really applies to any dependency that might change.  So hard linking the DLL can be problematic for a number reasons, but the primary reason is to not force loading of JSON.NET unless you actually need it when you use the JSON configuration features of the library.Enter Dynamic LoadingSo rather than adding an assembly reference to the project, I decided that it would be better to dynamically load the DLL at runtime and then use dynamic typing to access various classes. This allows me to run without a hard assembly reference and allows more flexibility with version number differences now and in the future.But there are also a couple of downsides:No assembly reference means only dynamic access - no compiler type checking or IntellisenseRequirement for the host application to have reference to JSON.NET or else get runtime errorsThe former is minor, but the latter can be problematic. Runtime errors are always painful, but in this case I'm willing to live with this. If you want to use JSON configuration settings JSON.NET needs to be loaded in the project. If this is a Web project, it'll likely be there already.So there are a few things that are needed to make this work:Dynamically create an instance and optionally attempt to load an Assembly (if not loaded)Load types into dynamic variablesUse Reflection for a few tasks like statics/enumsThe dynamic keyword in C# makes the formerly most difficult Reflection part - method calls and property assignments - fairly painless. But as cool as dynamic is it doesn't handle all aspects of Reflection. Specifically it doesn't deal with object activation, truly dynamic (string based) member activation or accessing of non instance members, so there's still a little bit of work left to do with Reflection.Dynamic Object InstantiationThe first step in getting the process rolling is to instantiate the type you need to work with. This might be a two step process - loading the instance from a string value, since we don't have a hard type reference and potentially having to load the assembly. Although the host project might have a reference to JSON.NET, that instance might have not been loaded yet since it hasn't been accessed yet. In ASP.NET this won't be a problem, since ASP.NET preloads all referenced assemblies on AppDomain startup, but in other executable project, assemblies are just in time loaded only when they are accessed.Instantiating a type is a two step process: Finding the type reference and then activating it. Here's the generic code out of my ReflectionUtils library I use for this:/// <summary> /// Creates an instance of a type based on a string. Assumes that the type's /// </summary> /// <param name="typeName">Common name of the type</param> /// <param name="args">Any constructor parameters</param> /// <returns></returns> public static object CreateInstanceFromString(string typeName, params object[] args) { object instance = null; Type type = null; try { type = GetTypeFromName(typeName); if (type == null) return null; instance = Activator.CreateInstance(type, args); } catch { return null; } return instance; } /// <summary> /// Helper routine that looks up a type name and tries to retrieve the /// full type reference in the actively executing assemblies. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetTypeFromName(string typeName) { Type type = null; // Let default name binding find it type = Type.GetType(typeName, false); if (type != null) return type; // look through assembly list var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // try to find manually foreach (Assembly asm in assemblies) { type = asm.GetType(typeName, false); if (type != null) break; } return type; } To use this for loading JSON.NET I have a small factory function that instantiates JSON.NET and sets a bunch of configuration settings on the generated object. The startup code also looks for failure and tries loading up the assembly when it fails since that's the main reason the load would fail. Finally it also caches the loaded instance for reuse (according to James the JSON.NET instance is thread safe and quite a bit faster when cached). Here's what the factory function looks like in JsonSerializationUtils:/// <summary> /// Dynamically creates an instance of JSON.NET /// </summary> /// <param name="throwExceptions">If true throws exceptions otherwise returns null</param> /// <returns>Dynamic JsonSerializer instance</returns> public static dynamic CreateJsonNet(bool throwExceptions = true) { if (JsonNet != null) return JsonNet; lock (SyncLock) { if (JsonNet != null) return JsonNet; // Try to create instance dynamic json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); if (json == null) { try { var ass = AppDomain.CurrentDomain.Load("Newtonsoft.Json"); json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); } catch (Exception ex) { if (throwExceptions) throw; return null; } } if (json == null) return null; json.ReferenceLoopHandling = (dynamic) ReflectionUtils.GetStaticProperty("Newtonsoft.Json.ReferenceLoopHandling", "Ignore"); // Enums as strings in JSON dynamic enumConverter = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.Converters.StringEnumConverter"); json.Converters.Add(enumConverter); JsonNet = json; } return JsonNet; }This code's purpose is to return a fully configured JsonSerializer instance. As you can see the code tries to create an instance and when it fails tries to load the assembly, and then re-tries loading.Once the instance is loaded some configuration occurs on it. Specifically I set the ReferenceLoopHandling option to not blow up immediately when circular references are encountered. There are a host of other small config setting that might be useful to set, but the default seem to be good enough in recent versions. Note that I'm setting ReferenceLoopHandling which requires an Enum value to be set. There's no real easy way (short of using the cardinal numeric value) to set a property or pass parameters from static values or enums. This means I still need to use Reflection to make this work. I'm using the same ReflectionUtils class I previously used to handle this for me. The function looks up the type and then uses Type.InvokeMember() to read the static property.Another feature I need is have Enum values serialized as strings rather than numeric values which is the default. To do this I can use the StringEnumConverter to convert enums to strings by adding it to the Converters collection.As you can see there's still a bit of Reflection to be done even in C# 4+ with dynamic, but with a few helpers this process is relatively painless.Doing the actual JSON ConversionFinally I need to actually do my JSON conversions. For the Utility class I need serialization that works for both strings and files so I created four methods that handle these tasks two each for serialization and deserialization for string and file.Here's what the File Serialization looks like:/// <summary> /// Serializes an object instance to a JSON file. /// </summary> /// <param name="value">the value to serialize</param> /// <param name="fileName">Full path to the file to write out with JSON.</param> /// <param name="throwExceptions">Determines whether exceptions are thrown or false is returned</param> /// <param name="formatJsonOutput">if true pretty-formats the JSON with line breaks</param> /// <returns>true or false</returns> public static bool SerializeToFile(object value, string fileName, bool throwExceptions = false, bool formatJsonOutput = false) { dynamic writer = null; FileStream fs = null; try { Type type = value.GetType(); var json = CreateJsonNet(throwExceptions); if (json == null) return false; fs = new FileStream(fileName, FileMode.Create); var sw = new StreamWriter(fs, Encoding.UTF8); writer = Activator.CreateInstance(JsonTextWriterType, sw); if (formatJsonOutput) writer.Formatting = (dynamic)Enum.Parse(FormattingType, "Indented"); writer.QuoteChar = '"'; json.Serialize(writer, value); } catch (Exception ex) { Debug.WriteLine("JsonSerializer Serialize error: " + ex.Message); if (throwExceptions) throw; return false; } finally { if (writer != null) writer.Close(); if (fs != null) fs.Close(); } return true; }You can see more of the dynamic invocation in this code. First I grab the dynamic JsonSerializer instance using the CreateJsonNet() method shown earlier which returns a dynamic. I then create a JsonTextWriter and configure a couple of enum settings on it, and then call Serialize() on the serializer instance with the JsonTextWriter that writes the output to disk. Although this code is dynamic it's still fairly short and readable.For full circle operation here's the DeserializeFromFile() version:/// <summary> /// Deserializes an object from file and returns a reference. /// </summary> /// <param name="fileName">name of the file to serialize to</param> /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param> /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param> /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param> /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns> public static object DeserializeFromFile(string fileName, Type objectType, bool throwExceptions = false) { dynamic json = CreateJsonNet(throwExceptions); if (json == null) return null; object result = null; dynamic reader = null; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var sr = new StreamReader(fs, Encoding.UTF8); reader = Activator.CreateInstance(JsonTextReaderType, sr); result = json.Deserialize(reader, objectType); reader.Close(); } catch (Exception ex) { Debug.WriteLine("JsonNetSerialization Deserialization Error: " + ex.Message); if (throwExceptions) throw; return null; } finally { if (reader != null) reader.Close(); if (fs != null) fs.Close(); } return result; }This code is a little more compact since there are no prettifying options to set. Here JsonTextReader is created dynamically and it receives the output from the Deserialize() operation on the serializer.You can take a look at the full JsonSerializationUtils.cs file on GitHub to see the rest of the operations, but the string operations are very similar - the code is fairly repetitive.These generic serialization utilities isolate the dynamic serialization logic that has to deal with the dynamic nature of JSON.NET, and any code that uses these functions is none the wiser that JSON.NET is dynamically loaded.Using the JsonSerializationUtils WrapperThe final consumer of the SerializationUtils wrapper is an actual ConfigurationProvider, that is responsible for handling reading and writing JSON values to and from files. The provider is simple a small wrapper around the SerializationUtils component and there's very little code to make this work now:The whole provider looks like this:/// <summary> /// Reads and Writes configuration settings in .NET config files and /// sections. Allows reading and writing to default or external files /// and specification of the configuration section that settings are /// applied to. /// </summary> public class JsonFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration> where TAppConfiguration: AppConfiguration, new() { /// <summary> /// Optional - the Configuration file where configuration settings are /// stored in. If not specified uses the default Configuration Manager /// and its default store. /// </summary> public string JsonConfigurationFile { get { return _JsonConfigurationFile; } set { _JsonConfigurationFile = value; } } private string _JsonConfigurationFile = string.Empty; public override bool Read(AppConfiguration config) { var newConfig = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfiguration)) as TAppConfiguration; if (newConfig == null) { if(Write(config)) return true; return false; } DecryptFields(newConfig); DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage"); return true; } /// <summary> /// Return /// </summary> /// <typeparam name="TAppConfig"></typeparam> /// <returns></returns> public override TAppConfig Read<TAppConfig>() { var result = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfig)) as TAppConfig; if (result != null) DecryptFields(result); return result; } /// <summary> /// Write configuration to XmlConfigurationFile location /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Write(AppConfiguration config) { EncryptFields(config); bool result = JsonSerializationUtils.SerializeToFile(config, JsonConfigurationFile,false,true); // Have to decrypt again to make sure the properties are readable afterwards DecryptFields(config); return result; } }This incidentally demonstrates how easy it is to create a new provider for the West Wind Application Configuration component. Simply implementing 3 methods will do in most cases.Note this code doesn't have any dynamic dependencies - all that's abstracted away in the JsonSerializationUtils(). From here on, serializing JSON is just a matter of calling the static methods on the SerializationUtils class.Already, there are several other places in some other tools where I use JSON serialization this is coming in very handy. With a couple of lines of code I was able to add JSON.NET support to an older AJAX library that I use replacing quite a bit of code that was previously in use. And for any other manual JSON operations (in a couple of apps I use JSON Serialization for 'blob' like document storage) this is also going to be handy.Performance?Some of you might be thinking that using dynamic and Reflection can't be good for performance. And you'd be right… In performing some informal testing it looks like the performance of the native code is nearly twice as fast as the dynamic code. Most of the slowness is attributable to type lookups. To test I created a native class that uses an actual reference to JSON.NET and performance was consistently around 85-90% faster with the referenced code. That being said though - I serialized 10,000 objects in 80ms vs. 45ms so this isn't hardly slouchy. For the configuration component speed is not that important because both read and write operations typically happen once on first access and then every once in a while. But for other operations - say a serializer trying to handle AJAX requests on a Web Server one would be well served to create a hard dependency.Dynamic Loading - Worth it?On occasion dynamic loading makes sense. But there's a price to be paid in added code complexity and a performance hit. But for some operations that are not pivotal to a component or application and only used under certain circumstances dynamic loading can be beneficial to avoid having to ship extra files and loading down distributions. These days when you create new projects in Visual Studio with 30 assemblies before you even add your own code, trying to keep file counts under control seems a good idea. It's not the kind of thing you do on a regular basis, but when needed it can be a useful tool. Hopefully some of you find this information useful…© Rick Strahl, West Wind Technologies, 2005-2013Posted in .NET  C#   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >