How to convert JSON text into objects using C# - c#

How can I convert the following JSON response to a C# object?
{
"err_code": "0",
"org": "CGK",
"des": "SIN",
"flight_date": "20120719",
"schedule": [
["W2-888","20120719","20120719","1200","1600","03h00m","737-200","0",[["K","9"],["F","9"],["L","9"],["M","9"],["N","9"],["P","9"],["C","9"],["O","9"]]],
["W2-999","20120719","20120719","1800","2000","01h00m","MD-83","0",[["K","9"],["L","9"],["M","9"],["N","9"]]]
]
}

To create a class off a json string, copy the string.
In Visual Studio, in the menu at the top, click Edit > Paste special > Paste Json as classes.
Install Newtonsoft.Json via Nuget
Paste the following code into your project, "jsonString" being the variable you want to deserialize :
Rootobject r = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonString);
Don't forget to rename Rootobject to be more descriptive eg ILoveTheSmellOfNapalmInTheMorning-that was a joke

First create a class to represent your json data.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer classe's instance. Your class should looks similar to the JSON structure (Properties)

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
Serialization Example:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Performance Comparison To Other JSON serializiation Techniques

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,
A cs class will be generated use that cs file as below:
var generatedcsResponce = JsonConvert.DeserializeObject<RootObject>(yourJson);
where RootObject is the name of the generated cs file;

This will take a json string and turn it into any class you specify
public static T ConvertJsonToClass<T>(this string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}

class Program
{
static void Main(string[] args)
{
var res = Json; //Json that has to be converted
Response resp = new Response();
resp = JsonSerializer.Deserialize<Response>(res);
Console.WriteLine(res);
}
}
public class Response
{
public bool isValidUser { get; set; }
public string message { get; set; }
public int resultKey { get; set; }
}

Related

Create JSON object from string in C#

I am trying to create a JSON string which contains one container and one array.
I can do this by using a stringbuilder but I am trying to find a better way to get the JSON string; I want:
{ "message":{ "text":"test sms"},"endpoints":["+9101234"]}
I tried this:
string json = new JavaScriptSerializer().Serialize(new
{
text = "test sms",
endpoints = "[dsdsd]"
});
And the output is:
{"text":"test sms","endpoints":"[dsdsd]"}
Any help or suggestions how to get the required format?
In the most recent version of .NET we have the System.Text.Json namespace, making third party libraries unecessary to deal with json.
using System.Text.Json;
And use the JsonSerializer class to serialize:
var data = GetData();
var json = JsonSerializer.Serialize(data);
and deserialize:
public class Person
{
public string Name { get; set; }
}
...
var person = JsonSerializer.Deserialize<Person>("{\"Name\": \"John\"}");
Other versions of .NET platform there are different ways like the JavaScriptSerializer where the simplest way to do this is using anonymous types, for sample:
string json = new JavaScriptSerializer().Serialize(new
{
message = new { text = "test sms" },
endpoints = new [] {"dsdsd", "abc", "123"}
});
Alternatively, you can define a class to hold these values and serialize an object of this class into a json string. For sample, define the classes:
public class SmsDto
{
public MessageDto message { get; set; }
public List<string> endpoints { get; set; }
}
public class MessageDto
{
public string text { get; set; }
}
And use it:
var sms = new SmsDto()
{
message = new MessageDto() { text = "test sms" } ,
endpoints = new List<string>() { "dsdsd", "abc", "123" }
}
string json = new JavaScriptSerializer().Serialize(sms);

Creating a JSON string, if the left-hand varaible has dashes in

I am trying to create a json string to send via a httprequest, I have json string like so:
{
"a-string": "123",
"another-string": "hello",
"another": "1"
}
My problem is, if I try and generate it like so
string json = new JavaScriptSerializer().Serialize(new
{
"a-string" = "123",
"another-string" = "hello",
"another" = "1"
});
Leads to:
So what is a way of trying to do the above, without getting that error?
Use Json NewtonSoft NuGet package. Then use my answer here to create a C# class for you json. Since your json has names in them which are not allowed as property names in C#, you can use the JsonPropety attribute so it can use it during serialization. Here is all of the code:
public class Rootobject
{
[JsonProperty("a-string")]
public string astring { get; set; }
[JsonProperty("another-string")]
public string anotherstring { get; set; }
public string another { get; set; }
}
public class Program
{
public static void Main()
{
var root = new Rootobject { another = "1", anotherstring = "hello", astring = "123" };
string json = JsonConvert.SerializeObject(root);
Console.Read();
}
}

How do deserialize JSON with non-standard (and varying) property names (in .NET)

I have to read a JSON stream (which I have no control over), which is in the form:
{"files":
{
"/some_file_path.ext": {"size":"1000", "data":"xxx", "data2":"yyy"},
"/other_file_path.ext": {"size":"2000", "data":"xxx", "data2":"yyy"},
"/another_file_path.ext": {"size":"3000", "data":"xxx", "data2":"yyy"},
}
}
So, I have an object named files, which has a number of properties, which have 1) different names every time, 2) different number of them every time, and 3) names with characters which can't be used in C# properties.
How do I deserialize this?
I'm putting this into a Portable Library, so I can't use the JavaScriptSerializer, in System.Web.Script.Serialization, and I'm not sure about JSON.NET. I was hoping to use the standard DataContractJsonSerializer.
UPDATE: I've changed the sample data to be closer to the actual data, and corrected the JSON syntax in the area the wasn't important. (Still simplified quite a bit, but the other parts are fairly standard)
You can model your "files" object as a Dictionary keyed by the JSON property name:
public class RootObject
{
public Dictionary<string, PathData> files { get; set; }
}
public class PathData
{
public int size { get; set; }
public string data { get; set; }
public string data2 { get; set; }
}
Then, only if you are using .Net 4.5 or later, you can deserialize using DataContractJsonSerializer, but you must first set DataContractJsonSerializerSettings.UseSimpleDictionaryFormat = true:
var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true };
var root = DataContractJsonSerializerHelper.GetObject<RootObject>(jsonString, settings);
With the helper method:
public static class DataContractJsonSerializerHelper
{
public static T GetObject<T>(string json, DataContractJsonSerializer serializer = null)
{
using (var stream = GenerateStreamFromString(json))
{
var obj = (serializer ?? new DataContractJsonSerializer(typeof(T))).ReadObject(stream);
return (T)obj;
}
}
public static T GetObject<T>(string json, DataContractJsonSerializerSettings settings)
{
return GetObject<T>(json, new DataContractJsonSerializer(typeof(T), settings));
}
private static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}
}
Alternatively, you can install Json.NET and do:
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
Json.NET automatically serializes dictionaries to JSON objects without needing to change settings.
We need to first convert this Invalid JSON to a Valid JSON. So a Valid JSON should look like this
{
"files":
{
"FilePath" : "C:\\some\\file\\path",
"FileData" : {
"size": 1000,
"data": "xxx",
"data2": "yyy"
},
"FilePath" :"C:\\other\\file\\path",
"FileData" : {
"size": 2000,
"data": "xxx",
"data2": "yyy"
},
"FilePath" :"C:\\another\\file\\path",
"FileData" : {
"size": 3000,
"data": "xxx",
"data2": "yyy"
}
}
}
To make it a valid JSON we might use some string functions to make it looks like above. Such as
MyJSON = MyJSON.Replace("\\", "\\\\");
MyJSON = MyJSON.Replace("files", "\"files\"");
MyJSON = MyJSON.Replace("data:", "\"data:\"");
MyJSON = MyJSON.Replace("data2", "\"data2\"");
MyJSON = MyJSON.Replace(": {size", ",\"FileData\" : {\"size\"");
MyJSON = MyJSON.Replace("C:", "\"FilePath\" :\"C:");
Than we can create a class like below to read the
public class FileData
{
public int size { get; set; }
public string data { get; set; }
public string data2 { get; set; }
}
public class Files
{
public string FilePath { get; set; }
public FileData FileData { get; set; }
}
public class RootObject
{
public Files files { get; set; }
}
Assuming you have a valid JSON you could use JavaScriptSerializer to return a list of objects
string json = "{}"
var serializer = new JavaScriptSerializer();
var deserializedValues = (Dictionary<string, object>)serializer.Deserialize(json, typeof(object));
Alternatively you could specify Dictionary<string, List<string>> as the type argument
strign json = "{}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var deserializedValues = serializer.Deserialize<Dictionary<string, List<string>>>(json);
foreach (KeyValuePair<string, List<string>> kvp in deserializedValues)
{
Console.WriteLine(kvp.Key + ": " + string.Join(",", kvp.Value));
}

JSON.Net Convert inner object to C# Model

I have the following JSON coming back from a remote API (I cannot modify the JSON returned)
{
"APITicket": {
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
}
Now using JSON.Net to convert to this to a model I have to create 2 models.
public class TicketModel
{
public string location { get; set; }
public string ticket { get; set; }
}
public class TicketContainer
{
public TicketModel APITicket { get; set; }
}
and do something like..
var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse);
and this works well - my problem arises when I have around 50 calls to make to the API and really dont fancy creating a second 'Container' for each. Is there a way to bind the example above directly to the TicketModel?
You can do it this way:
var json = #"
{
'APITicket': {
'location': 'SOMEVALUE',
'ticket': 'SOMEVALUE'
}
}";
//Parse the JSON:
var jObject = JObject.Parse(json);
//Select the nested property (we expect only one):
var jProperty = (JProperty)jObject.Children().Single();
//Deserialize it's value to a TicketModel instance:
var ticket = jProperty.Value.ToObject<TicketModel>();
use Newtonsoft's JArray to customize ur json before deserialize
public List<APITicket> JsonParser(string json)
{
Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.Parse(json);
var list = new List<APITicket>();
foreach(var item in jArray)
{
list.Add(
new APITicket { location = item["APITicket"]["location"],
ticket = item["APITicket"]["ticket"]
}
);
}
return list;
}
Modify the JSON so it looks like this
{
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
and do
List<TicketModel> tickets = JsonConvert.DeserializeObject<List<TicketModel>>(this.JSONResponse);
or even
Dictionary<string, string> tickets = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.JSONResponse);
so you don't need any models.

Deserialize JSON into string

How can I deserialize:
{
"data": [
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
}
to
class RawData
{
public string data { get; set; }
}
So, I just want to have
[
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
as value of property data of RawData's class instance.
Using Json.Net
var obj = (JObject)JsonConvert.DeserializeObject(json);
var newJson = obj["data"].ToString();
or using built-in JavaScriptSerializer
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
var newjson = new JavaScriptSerializer().Serialize(dict["data"]);
It would have made far much more sense to deserialize this JSON structure to:
public class Forecast
{
public IEnumerable<ForecastData> Data { get; set; }
}
public class ForecastData
{
public int ForecastID { get; set; }
public string StatusForecast { get; set; }
}
which is pretty trivial with the JavaScriptSerializer class that's built into the framework:
string json = "your JSON data here";
IEnumerable<ForecastData> data = new JavaScriptSerializer()
.Deserialize<Forecast>(json)
.Data;
or if you don't want to define models you could do that:
dynamic result = new JavaScriptSerializer().DeserializeObject(json);
foreach (var item in result["data"])
{
Console.WriteLine("{0}: {1}", item["ForecastID"], item["StatusForecast"]);
}

Categories

Resources