Writing and Reading to a Json format - c#

I have a large object in C# that i would like to write (serialize) to a .json file. I then want to read this .json file and be able to deserialize this object in javascript in order to display it on a website (after formatting it further in javascript). Can anyone tell me how i can achieve this serialization and deserialization to and from a properly formatted json file? Ive tried a few approaches but cant seem to achieve a tree like object structure in outputted file.
Thanks

If you are in a WebService you can set the [ScriptService] tag on your methods. If you are in a winforms or some other kind of app and need to use just serialize an object, you can tag your class serializable and then you can use the JavaSciptSerializer:
[Serializable]
public class MyClas
{
public int intVal { get; set; }
public double doubleVal { get; set; }
public string stringVal { get; set; }
}
In a method:
// Add a reference to System.Web.Extensions
// using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var myClass = new MyClas();
myClass.doubleVal = 42.00;
myClass.intVal = 42;
myClass.stringVal = "The answer";
MessageBox.Show(jss.Serialize(myClass));

JSON Lint could be what you're looking for on the client end. It's a pure javascript json validator/reformatter.
You can test the library here. It takes:
{"example" : "of", "json" : ["being", "reformatted"], "into" : {"something" : "pretty"}}
and makes it:
{
"example": "of",
"json": [
"being",
"reformatted"
],
"into": {
"something": "pretty"
}
}

Related

SerializationException: The data contract type <TypeName> could not be deserialized because more than one data item <FieldName> was found in the input

Im getting an 'SerializationException' exception when deserializing data's from json file:
public static T Deserialize(string FilePath)
{
using (FileStream FS = new FileStream(FilePath, FileMode.OpenOrCreate))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(FS) ?? null;
}
}
and this is how im trying to deserialize:
ServiceEntity resultEntity = JsonHelper<ServiceEntity>.Deserialize(DestinationFilePath);
while (resultEntity != null)
{
ListViewItem listViewItem = new ListViewItem(new string[] { resultEntity.ServiceName, resultEntity.ServiceStatus.ToString(), resultEntity.DisplayName });
lvServices.Items.Add(listViewItem);
}
T is this:
[DataContract]
sealed class ServiceEntity
{
[DataMember]
public string DisplayName { get; set; }
[DataMember]
public string ServiceName { get; set; }
[DataMember]
public ServiceControllerStatus ServiceStatus { get; set; }
}
JSON data is : https://pastebin.com/M18GD8yh
Your data is a single line of hundreds of JSON objects. The code reads the entire file and tries to deserialize it into a single C# object. You need to come up with a way to process each object separately. If you have control over the input file, it might be a good start to put the objects into an array, and deserialize that.
[{
"DisplayName": "AarSvc_2dae3",
"ServiceName": "AarSvc_2dae3",
"ServiceStatus": 1
},{
"DisplayName": "AMD External Events Utility",
"ServiceName": "AMD External Events Utility",
"ServiceStatus": 4
}, {
…
}]
what you call a json, is not a valid json string, it is just a collection of json-like peaces in one string. But you can easily fix it
string json = File.ReadAllText(filePath;
json="["+json.Replace("}{","},{")+"]";
after this you can parse it as Json Array
JArray services = JArray.Parse(json);
or you can deserialize it in your c# class
using Newtonsoft.Json;
List<ServiceEntity> services = JsonConvert.DeserializeObject<List<ServiceEntity>>(json);
or try your fancy serializer.
Output in a json format
[
{
"DisplayName": "AarSvc_2dae3",
"ServiceName": "AarSvc_2dae3",
"ServiceStatus": 1
},
{
"DisplayName": "AMD External Events Utility",
"ServiceName": "AMD External Events Utility",
"ServiceStatus": 4
},
....
]
UPDATE
If you have an acces to code to create a json from the c# object it is better to fix it there. IMHO you can use Newtonsonft.Json as a serializer . You can install it using a Nuget package. After this use this code
using Newtonsoft.Json;
List<ServiceEntity> services = ... your code to create list of services;
var json = JsonConvert.SerializeObject(services);
if you need to save this json in a file
File.WriteAllText(FilePath, json);

Trouble converting from JSON to C# objects - how do the classes work?

{
"device": "Lamp",
"type": "Switch",
"commands": [
{
"name": "turn Lamp on",
"command": "/api/Lamp/ON"
},
{
"name": "turn Lamp off",
"command": "/api/Lamp/OFF"
}
]
}
I need to deserialize the JSON into a(n) C# object(s). I am having trouble though understanding how to format the C# code. I used json2csharp.com and came up with this:
public class Command
{
public string name { get; set; }
public string command { get; set; }
}
public class RootObject
{
public string device { get; set; }
public string type { get; set; }
public List<Command> commands { get; set; }
}
However, I do not fully understand the two different objects. This is the C# code that returns a null value for command1:
HttpClient client = new HttpClient();
string url = "http://localhost:8080/api/whatcanisay/";
string json = await client.GetStringAsync(url);
Commands command1 = JsonConvert.DeserializeObject<Commands>(json);
TestOutput.Text = command1.command;
If someone could explain the classes and how they transfer over from the JSON, that would be really helpful.
This is JSON.net which is one of the most popular JSON framework for .NET.
Basically the way it works you define classes that matches the JSON schema, and then it turns the json string into C# objects.
The purpose is it makes it easier to parse the JSON data otherwise you would have to map each JSON values to your object properties manually.
It is an open source project, so feel free to read the code
https://github.com/JamesNK/Newtonsoft.Json
You can deserialize your JSON string using the Microsoft System.Web.Extensions and JavaScriptSerializer.DeserializeObject.
First, you must have classes associated to your JSON file. To create classes, select your JSON sample data and, in Visual Studio, go to Edit / Paste Special / Paste JSON As Classes.
Next, use this sample.
string json = await client.GetStringAsync(url);
var root = new JavaScriptSerializer().Deserialize<RootObject>(json);
// root object contains all JSON data.
Or you can also use a full JSON Library like http://www.newtonsoft.com/json

Convert Json Unicode to Utf8

I'm facing a wierd problem when converting Json Unicode(?) to UTF8
"V\u00E4xj\u00F6" should be "Växjö"
Right now it seems like I've tried everything possible, but no luck.
Any coding ninjas out there that may sit on a solution? I'm sure it's fairly easy but still can't seem to figure it out.
Thank you
As Tomalak pointed out, it can be done using the System.Web.Helpers.Json.Decode method (no external libraries, .NET Framework). You need to build a simple JSON object to fetch the decoded text:
// helper class
public class Dummy
{
public String Field { get; set; }
}
//
var value = "V\u00E4xj\u00F6";
var sb = new StringBuilder();
sb.Append("{");
sb.Append(String.Format(#"""Field"" : ""{0}""", value));
sb.Append("}");
var dummy = Json.Decode(sb.ToString());
Console.WriteLine(dummy.Field);
// it works also without helper class
var obj = Json.Decode(sb.ToString());
Console.WriteLine(obj.Field);
The output is:
Växjö
Växjö
One possibility would be to use the Json.NET library to decode the string (or maybe for the whole JSON handling?). The deserializer decodes the string automatically. My test code looks like this:
// placeholder for the example
public class Sample
{
public String Name { get; set; }
}
//
var i = #"{ ""Name"" : ""V\u00E4xj\u00F6"" }";
var jsonConverter = Newtonsoft.Json.JsonConvert.DeserializeObject(i);
Console.WriteLine(jsonConverter.ToString());
//
var sample = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(i);
Console.WriteLine(sample.Name);
The output is:
{
"Name": "Växjö"
}
Växjö

serialize json to object c#

I am new to json,I am trying to convert json response to object
the json is
"[{\"fields\":[[\"name\",\"value\",\"values\",\"error\"],[\"username\",\"test\",null,\"\"],[\"password\",\"test\",null,\"\"],[\"accountid\",\"\",null,\"\"],[\"rememberMe\",\"Y\",null,\"\"],[\"language\",\"en-US\",null,\"\"],[\"S\",\"test\",null,null]],\"success\":\"Y\",\"message\":\"User authenticated. Logging in.\"}]"
I wrote two classes
public class fields
{
public string name { get; set; }
public string value { get; set; }
public string values { get; set; }
public string error { get; set; }
}
public class Demo
{
public List<fields> fields { get; set; }
public string message { get; set; }
public string success { get; set; }
}
I made this Serialize code:
JsonSerializer serializer = new JsonSerializer();
Demo result = JsonConvert.DeserializeObject<Demo>(responseFromServer);
or this
Demo result = new JavaScriptSerializer().Deserialize<Demo>(responseFromServer);
the error is
Type '_Default+fields' is not supported for deserialization of an array
Thanks
Baaroz
I tried your code and it was a bit inconclusive for me. But I can show you what i've found and you can try working from here:
First: As I commented on your question, the first and last character of your string are [ and ]. That means your server is sending you an array. To solve that, i just changed your deserialization line to this:
Demo[] result = new JavaScriptSerializer().Deserialize<Demo[]>(responseFromServer);
Second: The code was still having troubles to deserialize to your fields object, then I realized you were receiving an array of an array of strings, then I changed your property in the Demo class to this:
public string[][] fields { get; set; }
Hope this can help.
If you format your json string you will notice that each entry in fields contains another four entries, therefore List<fields> fields will not suffice.
Replace it with List<List<string>> fields instead.
It is an issue with the Json not being a match with the objects you have.
If you want the JSON to match your C# models it would look like this:
[
{
"fields": [
{
"name": "Jeff",
"value": "xcv",
"values": "xcv",
"error": "xcv"
},
{
"name": "Jeff",
"value": "xcv",
"values": null,
"error": null
}
],
"success": "Y",
"message": "Userauthenticated.Loggingin."
}
]
try using this site (there are many more like it) to play about with your C# & JSON till you get what you are after: http://json2csharp.com/
I'm pretty convinced Newtonsoft is literally the best possible way to do anything with JSON in C# and without any headaches, it's the most popular C# NuGet package in the world with almost 1 billion downloads, works in ALL .NET versions basically.
I work with JSON and Web-based APIs regularly and will never use anything else in C# to handle JSON conversions.
Here's one of the simplest examples
string json_string = #"{
Firstname: ""Jane"",
Lastname: ""Doe"",
Age: 36,
IsEmployed: true,
IsMarried: true,
Children: 4
}";
var person = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json_string);
Console.WriteLine(person.Forename);
Console.WriteLine(person.Lastname);
Console.WriteLine(person.Age);
Console.WriteLine(person.IsEmployed);
Console.WriteLine(person.IsMarried);
Console.WriteLine(person.Children);
It generates objects on the fly, no matter the structure! Other solutions don't work in all .NET versions.
I wrote a simple, easy-to-follow article here https://turmanauli.medium.com/a-complete-guide-for-serializing-json-to-dynamic-objects-on-the-fly-in-c-7ab4799f648d
about how to install and use Newtonsoft via NuGet Package Manager in your Visual Studio project.

Deserializing JSON using C#

Finding some difficulty in sourcing information in trying to deserialize JSON in C#.
I have results from Google custom search returned in JSON format. I just want to check through my steps and establish the order in trying to deserialize it. Is this right?
I need to create classes to match
the JSON format. Kind of like a
creating schema file.
Use the JavaScriptSerializer() class and
deserialize method to extract the
relevant bits.
One of the issues I think I am going to run into is that I don't require all of the data returned but only the html links. How can I achieve that?
UPDATE
I have updated my question with the following JSON snippet and C# code. I want to output the string 'links' to console but it doesn't seem to be working. I think I am defining my classes wrongly?
JSON from Google Custom Search
handleResponse({
"kind": "customsearch#search",
"url": {
"type": "application/json",
"template": "https://www.googleapis.com/customsearch/v1?q\u003d{searchTerms}&num\u003d{count?}&start\u003d{startIndex?}&hr\u003d{language?}&safe\u003d{safe?}&cx\u003d{cx?}&cref\u003d{cref?}&sort\u003d{sort?}&alt\u003djson"
},
"queries": {
"nextPage": [
{
"title": "Google Custom Search - lectures",
"totalResults": 9590000,
"searchTerms": "lectures",
"count": 1,
"startIndex": 2,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"cx": "017576662512468239146:omuauf_lfve"
}
],
"request": [
{
"title": "Google Custom Search - lectures",
"totalResults": 9590000,
"searchTerms": "lectures",
"count": 1,
"startIndex": 1,
"inputEncoding": "utf8",
"outputEncoding": "utf8",
"cx": "017576662512468239146:omuauf_lfve"
}
]
},
"context": {
"title": "Curriculum",
"facets": [
[
{
"label": "lectures",
"anchor": "Lectures"
}
],
[
{
"label": "assignments",
"anchor": "Assignments"
}
],
[
{
"label": "reference",
"anchor": "Reference"
}
]
]
},
"items": [
{
"kind": "customsearch#result",
"title": "EE364a: Lecture Videos",
"htmlTitle": "EE364a: \u003cb\u003eLecture\u003c/b\u003e Videos",
"link": "http://www.stanford.edu/class/ee364a/videos.html",
"displayLink": "www.stanford.edu",
"snippet": "Apr 7, 2010 ... Course materials. Lecture slides · Lecture videos (2008) · Review sessions. Assignments. Homework · Reading. Exams. Final exam ...",
"htmlSnippet": "Apr 7, 2010 \u003cb\u003e...\u003c/b\u003e Course materials. \u003cb\u003eLecture\u003c/b\u003e slides · \u003cb\u003eLecture\u003c/b\u003e videos (2008) · Review sessions. \u003cbr\u003e Assignments. Homework · Reading. Exams. Final exam \u003cb\u003e...\u003c/b\u003e",
"cacheid": "TxVqFzFZLOsJ"
}
]
}
);
C# Snippet
public class GoogleSearchResults
{
public string link { get; set; }
}
public class Program
{
static void Main(string[] args)
{
//input search term
Console.WriteLine("What is your search query?:");
string searchTerm = Console.ReadLine();
//concantenate the strings using + symbol to make it URL friendly for google
string searchTermFormat = searchTerm.Replace(" ", "+");
//create a new instance of Webclient and use DownloadString method from the Webclient class to extract download html
WebClient client = new WebClient();
string Json = client.DownloadString("https://www.googleapis.com/customsearch/v1?key=My Key&cx=My CX&q=" + searchTermFormat);
//create a new instance of JavaScriptSerializer and deserialise the desired content
JavaScriptSerializer js = new JavaScriptSerializer();
GoogleSearchResults results = js.Deserialize<GoogleSearchResults>(Json);
Console.WriteLine(results);
//Console.WriteLine(htmlDoc);
Console.ReadLine();
}
}
Thanks
I use your #2 approach: deserialize with the JavaScriptSerializer.
This is what I do to deserialize a response from Facebook:
// get the id for the uploaded photo
var jss = new JavaScriptSerializer();
var resource = jss.Deserialize<Facebook.Data.Resource>(responseText);
....where Facebook.Data.Resource is defined like this:
namespace Facebook.Data
{
public class Resource
{
public string id { get; set; }
}
}
The responseText that I am deserializing from looks like this:
{"id":"10150111918987952",
"from":{"name":"Someone",
"id":"782272221"},
"name":"uploaded from Cropper. (at 12\/15\/2010 7:06:41 AM)",
"picture":"http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs817.snc4\/69790_101501113333332_782377951_7551951_8193638_s.jpg",
...
But since I have only one property defined in the Resource class, I only deserialize that. Define the fields in your class that you want to deserialize.
It works to use inheritance, of course. You can define your data classes like this:
namespace Facebook.Data
{
public class Resource
{
public string id { get; set; }
}
public class Person : Resource
{
public string name { get; set; }
}
}
...and then you can deserialize a Person object.
EDIT
Ok, given the sample json you provided in the updated question, here's how I wrote the classes to hold the response:
public class GoogleSearchItem
{
public string kind { get; set; }
public string title { get; set; }
public string link { get; set; }
public string displayLink { get; set; }
// and so on... add more properties here if you want
// to deserialize them
}
public class SourceUrl
{
public string type { get; set; }
public string template { get; set; }
}
public class GoogleSearchResults
{
public string kind { get; set; }
public SourceUrl url { get; set; }
public GoogleSearchItem[] items { get; set; }
// and so on... add more properties here if you want to
// deserialize them
}
And here's the C# code to deserialize:
// create a new instance of JavaScriptSerializer
JavaScriptSerializer s1 = new JavaScriptSerializer();
// deserialise the received response
GoogleSearchResults results = s1.Deserialize<GoogleSearchResults>(json);
Console.WriteLine(s1.Serialize(results));
Some comments:
The toplevel class to hold the search result is called GoogleSearchResults.
The first property in the GoogleSearchResults class is kind, corresponding to the first named property in the json object. You had link which isn't going to work, because link is not the name of a top-level property in that json object. There are properties lower in the hierarchy of your json named "link" but JavaScriptSerializer won't pull out those lower level things into the higher level.
The next property in my GoogleSearchResults class is of type SourceUrl. This is because the url property in the json is not a simple string - it is a json object with two properties, each with a string value. So SourceUrl as a class in C# gets two string properties, each with the appropriate name to deserialize one of those named properties.
the next property in the GoogleSearchResults class is called "items" so that it can deserialize the items dictionary from your json. Now items, as the name suggests, is an array in the json, as denoted by the square bracket around its value. This means there can be more than one item, although in your case there is just one item. So this property in C# must be an array (or collection). Each item in the json result is not a simple string, so, once again, as we did with SourceUrl, we need to define a holder class to deserialize the item object: GoogleSearchItem. This class has a bunch of simple string properties. The properties in the C# class could also be of type int or some other type, if that's what the json requires.
finally, when printing out the result, if you just call Console.WriteLine(result) you will see the result of the ToString() method that is implicitly invoked by Console.WriteLine. This will merely print the name of the type, in this case is "GoogleSearchResults", which is not what you want, I think. In order to see what's in the object, you need to serialize it, as I've shown. In the output of that, you will see only the values of things you deserialized. Using the classes I provided, the result will have less information than the original, because I didn't provide properties in the C# class corresponding to some of the json properties, so those weren't deserialized.
You could take a look at Json.NET and its LINQ support to create and query JSON. By crafting a nice LINQ query you will get only the stuff you need (you can select, group by, count, min, max, whatever you like).
http://msdn.microsoft.com/en-us/library/bb412170.aspx
http://msdn.microsoft.com/en-us/library/bb410770.aspx
Pull out the property you need after you have converted the JSON representation to a type in your C# app. I don't think there's a way to extract only one property from the JSON representation before you have converted it (though I am not sure).

Categories

Resources