Create Json in C# [duplicate] - c#

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 + " }";

Related

C# write object to file in human-readable text

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.

Converting a JObject to a dynamic object

I'm using a library developed by another developer in our company. One of the calls in this library returns a JObject. What I need to do is convert this JObject to a dynamic object and return it to my caller.
I've found lots of answers to create a dynamic with NewtonSoft JSON.Net but all the answers use JsonConvert.DeserializeObject which is not applicable in my case as I already have a JsonObject in hand.
Any solutions?
Well, I don't really understand your problem, but you can convert it like this:
dynamic result = yourJobject;

How to generate angularjs model from c# class

The angular app I am working on has several large input forms which span several pages. The data is added to an angular model which is a javascript object literal and sent to a webApi controller. The webApi parameter for my POST methods is a C# class (duh) with a lot of properties! Is there a utility which will generate the javascript from my C# class, so that my binding just works! I've googled this and failed even though it seems such a mundane task. As always thanks in advance.
You should use JSON serialize on your JS side and deserialize on your c# side.
JS:
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonParam = oSerializer.Serialize(param);
While on your c# side you should use something like, lets say your class is Person:
C#:
Person person = new JavaScriptSerializer().Deserialize<Person>(param);
see msdn documentation on serialize\deserialize json object

C# web service response arrays

I recently used C# to build a web service client. I chose C# because the web services components are powerful and easy (much easier to work with than Gsoap or Axis IMO).
My C# app runs in the background and should return data that other pieces of my application (which includes a web app, a PLC, and a database) can store and use.
My responses look something like this:
[
[
string
int
[]
]
string
[]
int
]
etc...
The point is that the return values are not simple. My question is what is the best way to reformat and consume this data from other parts of my application?
My choices are:
XML
JSON
I've checked out both routes and have not found a great way to serialize this data. Can anyone provide any recommendations?
Worst case scenario I may need to just create a common routine to build XML with StringBuilder, but I'm hoping there's something I don't know about yet (I'm new to C#) that will make my life easy.
You surelly can use JSON.
Use the JavaScriptSerializer class to serialize the data and your OK: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
var data = new { name = "someValue", id = 1 };
var json = new System.Web.Script.Serialization.JavaScriptSerializer();
return json.Serialize(data);
I haven't tested this code (I'm not in my dev machine by now), but I'm sure it works with some adjustments to your needs.
Why don't you create DTO classes for the return value and use either JSON or XML serialization? It is very convenient.

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