C# write object to file in human-readable text - c#

Do there exist any standard mechanisms or processes to output any C# object to file in human-readable text format ?
Unlike serialization ( BinaryFormatter.Serializer ) this would not ever require reading back the object from file.

There are many different "human readable" formats you could use to represent data (XML, JSON, YAML, etc). A common one is JSON.
There is a library called JSON.NET that is very heavily used in the .NET community for handling JSON. You can use built in .NET methods but I prefer this nuget package. With JSON.NET you can do something as simple as:
MyClass someObject = new MyClass();
someObject.SomeProperty = "Foo";
someObject.SomeOtherProperty = "Bar";
string json = JsonConvert.SerializeObject(someObject);
That string "json" would look similar to this:
{
"SomeProperty":"Foo",
"SomeOtherProperty":"Bar"
}
I made a fiddle here that shows a sample class I created and how it looks when its serialized into JSON.

Related

How to serialize protobuf from json with auto ignoring unknown fields in c#?

For example, I have a proto like this:
message ProtoType
{
string field1 = 1;
strin field2 = 2;
}
And I have a json deserialized from a newer version of this proto:
{
"field1": "111",
"field2": "222",
"testField": "test"
}
I use this to serialize protobuf from json:
JsonParser.Default.Parse<ProtoType>(protojson);
However, if my json has some fields that don't exist in proto (like the testField below), it will throw an exception:
InvalidProtocolBufferException: Unknown field: testField
I wonder if there's a way to get a ProtoType instance which can automatically ignore unknown fields.
Thanks a lot!
You will need to use the class JsonParser.Setting and use the function WithIgnoreUnknownFields. So you will have something like this:
var settings = JsonParser.Settings.Default.WithIgnoreUnknownFields(true);
var t = new JsonParser(settings).Parse<Test.ProtoType>(protojson);
Furthermore, the documentation doesn't seem to be covering that. I recommend that you check the JsonParser source code and search for the Settings class to get all the functions you can use.
Edit
For completeness, there is a copy of the C# documentation managed by the Google cloud team and this one is up-to-date.

Read structured data from OPC UA server

I'm triying to read some data form an OPC UA server using opc-ua-client library. Managed to connect to server and read some simple variables, but facing issues when reading structured values. However, I'm able to browse those structured values using 3rd party tools, such as UAExpert.
This is the code snippet:
var readRequest = new ReadRequest
{
NodesToRead = new[] { new ReadValueId { NodeId = NodeId.Parse(nodeId), AttributeId = AttributeIds.Value } }
};
var response = channel.ReadAsync(readRequest).Result;
var result = response.Results[0].GetValueOrDefault<ExtensionObject>();
The point is: how should I cast the ExtensionObject into the underlying real object? Response's body is binary serialized into a System.Byte[] field, and don't know how to deserialize it. I know the fields and types of the structure, so defined it in the code (even decorating with the namespace provided by the server) as follow:
[BinaryEncodingId("nsu=urn:OMRON:NxOpcUaServer:FactoryAutomation;i=5005")]
private class MES_WRITE_STRUCT : Structure
{
uint Message_NUM { get; set; }
//Some other fields
DateTime Time_Stamp { get; set; }
}
Things I've tried (and failed) so far:
Brute-force cast:
var eObject = (MES_WRITE_STRUCT)result.GetValueOrDefault<ExtensionObject>();
Read the response as the expected type rather than using generic object:
var eObject = result.GetValueOrDefault<MES_WRITE_STRUCT>();
Use the Variant property rather than Value (same result as
using Value):
result.Variant.GetValue();
Create a binary reader and attempt to deserialize it into expected
class.
Maybe I'm using a wrong approach and structured values should be read in a different way. Or even the library does not support structured variables (not much documentation available). Or just using an incorrect type when defining custom class in .NET and hence casting is failing.
I'm totally stuck, any information or guidance is wellcome.
PS: I'm not tied to this library and can switch to another one (preferably with no licenses, but if really worths can consider buying).
One way would be to use the XML description of the information model (so called nodesets) you wish to consume and use the model compiler from OPC Foundation to generate C# classes out of it. Those classes can be integrated in your solution and used for deserialization.
And example (using the OPC Foundation libraries) could be found here
Another way is the OPC Foundation .NET Standard client which has an extension library nuget package called complex client. It contains the logic to read the structured type definition from a server from a dictionary (V1.03) or using DataTypeDefinition (V1.04).
Based on the obtained type definition the classes for the structured types can be emitted for encoding/decoding the byte string in the extension object at runtime. Please open issues if the complex client has difficulties to decode your structured type.

Dummy Objects Good or Bad

I am working on a project that communicates a lot of data with a server. This data is in a json format. We end up creating a lot of dummy objects to parse the json data. This leads to having a lot of classes that just contain class members. Is there a better way of doing things?
thanks
Assuming that you are using NewtonSoft's JSON parser or something similar, you have a couple of choices here. The usual use case here is to deserialize to a named type, thus:
var parsedMessage = JsonConvert.DeserializeObject<Message>(content.AsString());
If you have many types for each differnet JSON message type you wish to receive and wish to avoid to, you can do the following:
var parsedMessage = JsonConvert.DeserializeObject<dynamic>(content.AsString());
This will give you a dynamic object that you can inspect and should also work given other Json libraries. Alternatively, NetwtonSoft also provides the following method:
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject);
This will allow you to deserialize to an anonymously typed object rather than a dynamic object.

Create Json in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create JSON string in C#
I want to use google chart in mt ASP.NET MVC application. There is no mvc examples in there and datatable struct. I have never worked Json before and I must create a json like following code.
How can I create like this in C#
{"cols":[
{"id":"","label":"Month","pattern":"","type":"string"},
{"id":"","label":"Sales","pattern":"","type":"number"},
{"id":"","label":"Expenses","pattern":"","type":"number"}],
"rows":[
{"c":[
{"v":"April","f":null},
{"v":1000,"f":null},
{"v":900,"f":null},
{"c":[
{"v":"July","f":null},
{"v":1030,"f":null},
{"v":null,"f":null},
"p":null
}
I cant find easy examples about creating json in C#. Please Help me.
Thanks.
Give Json.NET a try. I think it will give you what you need.
Follow a nice article about this on code project
http://www.codeproject.com/Articles/78928/Create-JSON-from-C-using-JSON-Library
Create it as a normal class with properties, then:
var json = new JavaScriptSerializer().Serialize(myObject)
or a dynamic object:
var json = new JavaScriptSerializer().Serialize(new { property = "string" })
Well you can use DataContractJsonSerializer Class to Serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects. in .net 4.0.
I hope you have checked How to create JSON string in C# and this is not duplication of the same.
Apart from that you can have option to use WCF services that produce RESTful Service and JSON data. You can check this example that is best example to suit your needs in WCF.
Another approach is if you like some built in library then Json.Net is one of the good library around on codeplex.
I would try the JSON.NET library. It has advantages of most of the serializers built into .NET in terms of both capability and performance. And I believe Microsoft will be bundling the JSON.NET library with ASP.NET 4.5 as a result.
Have a look at this code.
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = int.MaxValue;
string sa = oSerializer.Serialize(p); // where p is your object to serialize.
sa = "{ \"Result\": " + sa + " }";

How to dynamically create a JSON object in c# (from an ASP.NET resource file)?

I need to serialize the strings from a resource file (.resx) into a JSON object. The resource file's keys are in flux and thus I cannot just create a C# object that accepts the appropriate values. It needs to be a dynamic solution. I am able to loop through the key-value pairs for the file, but I need an easy way to serialize them to JSON.
I know I could do:
Object thing = new {stringOne = StringResource.stringOne; ...}
But, I'd rather have something like:
Object generic = {}
foreach (DictionaryEntry entry in StringResource) {
generic.(entry.Key) = entry.Value
}
Or should I just create a custom JSON serializer that constructs the object piecemeal (i.e. foreach loop that appends part of the JSON string with each cycle)?
EDIT
I ended up writing a quick JSON serializer that constructs the string one field at a time. I didn't want to include a whole JSON library as this is the only use of JSON objects (for now at least). Ultimately, what I wanted is probably impractical and doesn't exist as it's function is better served by other data structures. Thanks for all the answers though!
If you're using C# 4.0, you should look at the magical System.Dynamic.ExpandoObject. It's an object that allows you to dynamically add and remove properties at runtime, using the new DLR in .NET 4.0. Here is a good example use for the ExpandoObject.
Once you have your fully populated ExpandoObject, you can probably easily serialize that with any of the JSON libraries mentioned by the other excellent answers.
This sounds like an accident waiting to happen (i.e. creating output prior to cementing the structure), but it happens.
The custom JSON serializer is a compelling option, as it allows you to easily move from your dictionary into a JSON format. I would look at open source libraries (JSON.NET, etc) to see if you can reduce the development time.
I also think setting up in a slightly more structured format, like XML, is a decent choice. It is quite easy to serialize from XML to JSON using existing libraries, so you avoid heavy customization/
The bigger question is what purposes will the data ultimately serve. If you solve this problem using either of these methods, are you creating bigger problems in the future.
Probably I would use JSON.NET and the ability to create JSON from XML.
Then, you could create an XML in-memory and let JSON.NET convert it to JSON for you. Maybe if you dig deeper into the API, there are other options, too.
Newtonsoft is a library that has all kinds of nifty JSON tools...among them, on-the-fly one-line serializer and deserializers...check it out, it's my favorite JSON library out there
http://james.newtonking.com/pages/json-net.aspx
If I remember correctly, it has a class that will convert JSON to a .NET object without having to create the .NET object first. Think it is in the Json.Convert class
The way I do it is:
var serialiser = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serialiser.Serialize(data);
context.Response.Write(json);

Categories