Read and parse JSON data - c#

I'm new to c# and I tried to parse the JSON data from WSDL service.
Here is the code:
string cityjson = service.getcity();
/*
sample cityjson return
[{"City":"Alaminos","Province":"Pangasinan"},{"City":"Angeles","Province":"Pampanga"},{"City":"Antipolo","Province":"Rizal"}]
*/
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(cityjson)))
{
var serializer = new DataContractJsonSerializer(typeof(Location));
Location locs = (Location)serializer.ReadObject(ms);
Console.WriteLine(locs.Locations); // blank in console output.
}
and here is my datacontract code
[DataContract]
public class Location
{
[DataMember]
public String[] Locations;
}
when I do console.WriteLine(cityjson); it prints the whole json.

Your C# class is wrong.It should have two properties City and Province.And the json object is a List of Locations. And try to use JSON.Net to parse your json data.It's lightweight and easy to use.Also you could use available resources to convert json to C# types.
public class Location
{
public String City { get; set; }
public String Province { get; set; }
}
var t = "[{'City':'Alaminos','Province':'Pangasinan'},{'City':'Angeles','Province':'Pampanga'},{'City':'Antipolo','Province':'Rizal'}]";
var type = JsonConvert.DeserializeObject<List<Location>>(t);

use the namespace System.Web.Script.Serialization;
Rewrite your code like this
JavaScriptSerializer js = new JavaScriptSerializer();
Location locs = js.Deserialize<Location>(ms);

Related

Passing a json file as a parameter to a method

I am learning how to work with json data using Newtonsoft.Json.
I stored my valid json file in a folder in my console application and calling
a method that will process the json file.
static void Main(string[] args)
{
IEnumerable<IEnumerable<string>> result;
string pathToFile = #"C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
MyReader objReader = new MyReader();
result = objReader.Export(pathToFile).ToList();
Console.WriteLine("Hello");
}
Here is the method within my class that is been called.
public IEnumerable<IEnumerable<string>> Export(string json)
{
var document = JToken.Parse(json);
var data = new List<List<string>>();
.....
return data;
}
I am beginning to feel I cannot use a pathToFile as a path to my json file.
I started to get the error message below on this line [var document = JToken.Parse(json);]
Newtonsoft.Json.JsonReaderException:
'Unexpected character encountered while parsing value: C. Path '', line 0, position 0.'
How do I resolve this error message?
The Newtonsoft Json.NET documentation has two examples showing how to deserialize JSON from a file. Below are both examples with minor modifications to help integrate with your code.
Option 1. Reading JSON data via JsonConvert
var pathToFile = #"C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
// read file into a string and deserialize JSON to a type
var dataFromJsonConvert = JsonConvert.DeserializeObject<MyData>(File.ReadAllText(pathToFile));
// dataFromJsonConvert now holds your JSON data from file
Option 2. Reading JSON data via JsonSerializer
var pathToFile = #"C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(pathToFile))
{
var serializer = new JsonSerializer();
var dataFromJsonSerializer = (IEnumerable<IEnumerable<string>>)serializer.Deserialize(file, typeof(MyData));
// dataFromJsonSerializer now holds your JSON data from file
}
Example demonstrating how to utilize answer
static void Main(string[] args)
{
var pathToFile = "C:\DevelopmentJson\ConsoleApp1\File\my_test.json";
var fileJsonRaw = File.ReadAllText(pathToFile))
var objReader = new MyReader();
var fileJsonParsed = objReader.Export(fileJsonRaw).ToList();
Console.WriteLine("Hello");
}
public MyData Export(string json)
{
return JsonConvert.DeserializeObject<MyData>(json);
}
Classes generated from your JSON data
The classes below were generated from your sample JSON. These classes are used within answer to demonstrate a complete solution.
public partial class MyData
{
[JsonProperty("UpdatedDay")]
public string UpdatedDay { get; set; }
[JsonProperty("UpdatedUser")]
public string UpdatedUser { get; set; }
[JsonProperty("solution")]
public Solution[] Solution { get; set; }
}
public partial class Solution
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("fields")]
public Field[] Fields { get; set; }
}
public partial class Field
{
[JsonProperty("firstname")]
public string Firstname { get; set; }
[JsonProperty("lastiname", NullValueHandling = NullValueHandling.Ignore)]
public string Lastiname { get; set; }
[JsonProperty("required")]
public bool FieldRequired { get; set; }
[JsonProperty("lastname", NullValueHandling = NullValueHandling.Ignore)]
public string Lastname { get; set; }
}
Note: The following using statements are necessary.
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
JToken.Parse doesn't take a path, it takes the actual json string.
You can get the contents of the file with File.ReadAllText.
Something like this (checks etc omitted):
public IEnumerable<IEnumerable<string>> Export(string path)
{
string json = File.ReadAllText(path);
var document = JToken.Parse(json);
var data = new List<List<string>>();
.....
return data;
}
Note that there are better ways of parsing a file with json.net. For more info read this.

C# serialize JSON without property name

maybe this was asked somewhere before, but I don't know how to search for my problem.
I'm using a WebAPI to verify licenses. From this API I get the return JSON string in follwing format.
string json = "[{"status":"error","status_code":"e002","message":"Invalid licence key"}]"
This is my serializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl));
ActivationResponseWooSl ar = (ActivationResponseWooSl)js.ReadObject(ms);
}
Now my questions is, how must the "ActivationResponseWooSl" class look like so that the serializer can convert it?
Any help is highly appreciated!
For now it looks like that (what's not workiing):
[DataContract]
public class ActivationResponseWooSl
{
[DataMember(Name = "status")]
public string Status { get; set; }
[DataMember(Name = "status_code")]
public string ErrorCode { get; set; }
[DataMember(Name = "message")]
public string ErrorMessage { get; set; }
}
However when I serialize my json string, all properties are "null".
Your class is correct. Your JSON is an array of object.
Try
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl[]));
var arr = (ActivationResponseWooSl[])js.ReadObject(ms);

Retrieving data from an Object(deserialized json) in C#

I have a JSON string that I am trying to parse, using C#. I have used JsonConvert to serialize my data into a JSON string.
Here is my sample JSON string:
{"names": ["John", "Joe", "Jack"], "nationality": "American"}
I am able to deserialize this string into an object using JsonConvert.DeserializeObject(x);
The problem is, I dont know how to read from the object, using C#. Can someone help me out?
public class People
{
[JsonProperty("names")]
public List<string> Names;
[JsonProperty("nationality")]
public string Nationality;
}
Other answers are technically correct, but using JsonPropertyAttribute is a universally accepted convention. Then use JsonConvert:
var people = JsonConvert.DeserializeObject<People>(x);
A better approach would be to define a class with the expected structure, then using JavaScriptSerializer to deserialize it:
class NameSet
{
public IList<string> names { get; set; }
public string nationality { get; set; }
}
var serializer = new JavaScriptSerializer();
var nameset = serializer.Deserialize<NameSet>(jsonString);
Create a custom class like this:
public class CustomData
{
public string[] Names { get; set; }
public string Nationality { get; set; }
public CustomData() { }
}
And use JsonConvert to deserialize yo an object of this type:
CustomData data = JsonConvert.DeserializeObject<CustomData>(x);
The following should suffice:
public class PeopleGroup {
public string[] names { get; set; }
public string nationality { get; set }
}
var myObject = JsonConvert.DeserializeObject<PeopleGroup>(x);
Basically, you create a strongly typed object, and deserialise directly into it.
If you don't want to actually define a class, you can use an anonymous type:
string json = "{\"names\": [\"John\", \"Joe\", \"Jack\"], \"nationality\": \"American\"}";
// Just defining the structure of the anonymous type
var x = new { names = new string[0], nationality = string.Empty };
x = JsonConvert.DeserializeAnonymousType(json, x);
You should use dataContractJsonSerializer class, it is faster and most important is it is inbuilt class of .Net Framework. I will post solution in my next commment, in that How can we use DataContractJsonSerializer class.Now I cant post solution because in my end net is too slow :(, but I will post today.

Deserialization of Json without name fields

I need to deserialize the following Json, which according to Jsonlint.com is valid, but ive not come across this before or cannot find examples of similar Json and how to deal with it?
[1,"Bellegrove / Sherwood ","76705","486","Bexleyheath Ctr",1354565507000]
My current system with like this:
Data class:
[DataContract]
public class TFLCollection
{ [DataMember(Name = "arrivals")]
public IEnumerable<TFLB> TFLB { get; set; }
}
[DataContract]
public class TFLB
{
[DataMember]
public string routeName { get; set; }
[DataMember]
public string destination { get; set; }
[DataMember]
public string estimatedWait { get; set; }
}
Deserializer:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TFLCollection));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result)))
{ var buses = (TFLCollection)serializer.ReadObject(stream);
foreach (var bus in buses.TFLBuses)
{
StopFeed _item = new StopFeed();
_item.Route = bus.routeName;
_item.Direction = bus.destination;
_item.Time = bus.estimatedWait;
listBox1.Items.Add(_item);
My exsiting deserializer works with a full Json stream and iterates through it, but in my new Json I need to deserialize, it only have 1 item, so I wont need to iterate through it.
So is it possible to deserialize my Json example using a similar method than I currently do?
I would say that you are attempting to overcomplicate things. What you have is a perfectly formed json array of strings. If I were you I would deserialize that to an .net array first, and then write a 'mapper' function to copy the values across:
public TFLB BusRouteMapper(string[] input)
{
return new TFLB {
Route = input[x],
Direction = input[y],
};
}
And so on. Of course this assumes that you know what order your json is going to be in, but if you are attempting this in the first place then you must do!

How can I convert JSON to DataTable using C#

I have a json string and would like to make a DataTable from it.
How can I convert JSON to a DataTable in C#?
Update:
I have used Json.Net as per link provided here
and build 2 class to to handle json string as per below
public class JsonHelper
{
public List<User> userdata { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
public DateTime createdDate { get; set; }
}
and use following code to Deserialize
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
StringReader sr = new StringReader(jsonstr);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, typeof( JsonHelper));
reader.Close();
return result;
but getting following error
Cannot deserialize JSON array into type 'mynamespace+JsonHelper'.
What should be problem here , please help me to sort out this problem.
thanks.
This post by Rick Strahl may help you out. Under the covers he's using Newtonsoft's JSON.NET libraries to do the heavy lifting.

Categories

Resources