How read JSON file in C#? [duplicate] - c#

I have about 7000 lines of JSON data that I want to parse. An example of just part of it can be seen here. What I did was use WebRequest and StreamReader to put all the data into a string. (Oddly, it puts all of the data into one VERY long line). But now I want to parse this and I am not sure how. Can anyone explain how to use Deserialize? I have parsed JSON data with Java before but I am having trouble doing so with C# especially with my inability to find documentation with clear examples. Any help will be greatly appreciated.

Try JSON.Net, if you have not seen this it should help you.
Json.NET library makes working with
JSON formatted data in .NET simple.
Key features include a flexible JSON
serializer to for quickly converting
.NET classes to JSON and back again,
and LINQ to JSON for reading and
writing JSON.
Deserialization discussed here.
The quickest method of converting
between JSON text and a .NET object is
using the JsonSerializer. The
JsonSerializer converts .NET objects
into their JSON equivalent and back
again.
The basic code structure for deserialization is below - Target still needs to be filled out to capture the rest of the parsed data items with the appropriate type. The file mentioned json.txt contains your data from the URL above.
using System;
using System.IO;
using Newtonsoft.Json;
public class NameAndId
{
public string name;
public int id;
}
public class Data
{
public NameAndId[] data;
}
public class Target
{
public string id;
public NameAndId from;
public Data likes;
}
public class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText(#"c:\temp\json.txt");
Target newTarget = JsonConvert.DeserializeObject<Target>(json);
}
}
Here is the first part of the JSON stream for reference:
{
"id": "367501354973",
"from": {
"name": "Bret Taylor",
"id": "220439"
},
"message": "Pigs run from our house in fear. Tonight, I am wrapping the pork tenderloin in bacon and putting pancetta in the corn.",
"updated_time": "2010-03-06T02:57:48+0000",
"likes": {
"data": [
{
"id": "29906278",
"name": "Ross Miller"
},
{
"id": "732777462",
"name": "Surjit Padham"
},

Personally I don't like carrying around dependencies on external libraries when the functionality is provided by the framework. In this case, the JavaScriptSerializer class:
var serializer = new JavaScriptSerializer();
var myobj = serializer.Deserialize<MyType>(mystring);

Related

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

Proper use of "$ref" property in JSON Pagination / Json.net

I'm trying to write a C# class for a RESTful web service which returns some items but uses JSON Pagination. I'm using JSON.net for serialization and deserialization.
I have the following code:
static void RefTest()
{
PageTest PageToTest = new PageTest();
PageToTest.next = new PageTest.PageLink();
PageToTest.next.reference = "https://www.example.com/RESTQuery/?page=1";
PageToTest.items = new List<string>();
PageToTest.items.Add("Car");
PageToTest.items.Add("Truck");
PageToTest.items.Add("Plane");
string JSON = JsonConvert.SerializeObject(PageToTest);
PageTest DeserializedPageTest = JsonConvert.DeserializeObject<PageTest>(JSON);
}
While the class looks as follows:
public class PageTest
{
public PageLink next;
public List<string> items;
public class PageLink
{
[JsonProperty("$ref")]
public string reference;
}
}
When I serialize that to a string, I get the expected result:
{
"next": {
"$ref":"https://www.example.com/RESTQuery/?page=1"
},
"items":
[
"Car",
"Truck",
"Plane"
]
}
Until now, everything works fine, it looks like json.net doesn't do anything special with the $ref property when serializing to a string.
Upon parsing of the string, however, json.net recognized the property named "$ref" as an reference to some id (which it can't find) and does NOT put it back on the deserialized object.
This is to be expected, but the web service is handing out pagination that way (With "next", "previous" and "last" attributes).
Basically, since it's impractical (I guess?) for the server to just give me all the values I will have to live with the pagination. So when I want to get all the items, I will have to deserialize the JSON response, check for additional items (indicated when there is a "next" property) and do the process again, until I have retrieved all the data I want.
Do you have any ideas on how I could handle that?
Thanks!

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.

Trying to parse data from a website and deserializing it in C#

I'm trying to parse data from my website and then deserializing it inside C# but I haven't gotten it work. What is the simplest way and method to use when grabbing data from a http source and deserializing it in C#?
Based on the following JSON:
{
name: "Brad Christie",
score: 10,
questions: [
{
question_id: 1,
question: "How do I deserialize javascript?",
answer: "JavaScriptSerializer",
points: 10
}
]
}
and assuming these classes:
public class Question
{
public Int32 question_id;
public String questions;
public String answer;
public Int32 points;
}
public class JSExample
{
public String name;
public Int32 score;
IEnumerable<Question> questions;
}
the below should work (though didn't test and going by memory of what I've done in the past). Basically, the JavaScriptSerializer should take a JSON string and parse it out in to your custom object, or result in a dictionary of the structure of the JSON (I personally prefer placing it an object so i can manipulate it as I chose, but you can use the dictionary/dynamic variable and debug to see the result). Anyways, the code would be as follows:
//String the_JSON_string = <data from webpage>;
JavaScriptSerializer serializer = new JavaScriptSerializer();
JSExample example = serializer.Deserialize<JSExample>(the_JSON_string);
There are a number of JSON serializers in .NET. Most notably the built in DataContractSerializer
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
EDIT:
(Sorry wrong link, here's the one for JSON
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
and http://msdn.microsoft.com/en-us/library/bb410770.aspx)
and JSON.NET
http://json.codeplex.com/

Deserialize Json in C#

{
"person": "david",
"images": {
"usable_sizes": [
[
[150,
41
],
"image1.png"
],
[
[220,
61
],
"image2.png"
],
[
[220,
61
],
"image3.png"
]
],
"uploader": null
}
}
I am using a JavaScriptSerializer in C# to parse some JSON. The above is the string I get back from the webrequest. Calling Deserialize on the string puts the Person in the right place in the object, but I don't know what type to use for the array nested under "images." I am at a complete loss.
here is relevant code:
TopLevelObject topObj = new JavaScriptSerialize().Deserialize<TopLevelObj>(jsonStream);
public TopLevelObject
{
public string person;
public imgStruct images;
}
public class imgStructure
{
public List<string[,][]> available_sizes;
}
but that's not taking. I have tried a variety of other forms for the class, but can't get the deserialize to put the data in without proper keys. I have no ability to change the inbound JSON as I am consuming it from a third party.
This is what I believe your classes should look like:
public class RootObj
{
public string person;
public ImageDataObj images;
}
public class ImageDataObj
{
public object uploader;
public List<List<object>> usable_sizes
}
As you can see the inner list is a list of objects. That is because the list has items of different types: one is a list (numerical data [150, 41]) and the other is a string (image name). I do not think you can strongly type the inner list for that reason.
Maybe it is worth examining on runtime (using the VS debugging tools) the structure of the objects inside the inner list and that could give you an indication of how to map it.
How the usable_images property type does look like if you take it to its detail is:
public List<List<Dictionary<List<int>,string>>> usable_sizes
but that is just a guess.
I would advise going to JSON.org and using one of their pre-built solutions.

Categories

Resources