How can I deserialize JSON data to this class structure? - c#

So basically I want to deserialize JSON data from sepcific URL to this class structure and then use it to display it on a page.
I don't understand how should I deserialize it because there are two classes that are compatible with JSON structure on the url.
This is the code shown below.
public class IndexModel : PageModel
{
public void OnGet()
{
Rootobject rootobject = new Rootobject();
rootobject.regions[0] = _download_serialized_json_data<Region>("https://visservice.meteoalarm.org/api/v1/regions?language=ATOM");
}
private static Region _download_serialized_json_data<Region>(string url) where Region : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<Region>(json_data) : new Region();
}
}
public class Rootobject
{
public Region[] regions { get; set; }
}
public class Region
{
public bool active { get; set; }
public float[][] bb { get; set; }
public string code { get; set; }
public string name { get; set; }
}
}
Edit:
Value of json_data:

As per your class definitoins, it should be JsonConvert.DeserializeObject<Rootobject>(json_data)

Related

How to convert a Json string to List in c#

In web service i am try to convert a jzonString to a list.
{
"name": "Test",
"Fname": "Testing",
"S1": "Content1",
"S2": "Content2",
"S3": "Content3"
}
[WebMethod]
public int Create(string Detils, string Companyid)
{
try
{
dynamic ScheduleShift = new JavaScriptSerializer().DeserializeObject(Detils);
\\ i need to set data to list or to an object
InvDetails objDetails = new InvDetails();
List<InvDetails> lstDetails = new List<InvDetails>();
return objDetails.CreateInvDetails(objDetils);
}
catch (Exception ex)
{
// Abort Transaction
throw ex;
}
}
Created another library file to declare the object and to insert into db
public class Inventory
{
CommonExecDAL CommonExecDAL = new CommonExecDAL();
public string name { get; set; }
public string Fname { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public int intCompanyId { get; set; }
public int CreateInvComputer(InvDetails objInvDetails)
{
SqlParameter[] arParms = new SqlParameter[6];
.........
}
}
If you don't want to create a class :
You can use JObject.Parse() method for deserializing dynamically.
As #SirRufo said, you can deserialize a JSON array into a list. but your JSON string in the sample is a single object!
Anyway, you deserialize JSON string to object with the use JSON.Net.
First, you have a class for Deserialize :
public class Data
{
public string name { get; set; }
public string Fname { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
}
Then you can deserialize JSON string to C# class :
var obj = JsonConvert.DeserializeObject<Data>(jsonString);
Just add reference to System.Web.Extensions ,(built in dll on .NET 4+) :
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObj =jss.Deserialize<dynamic>(jsonString);

using JSON response from REST api with nonstandard names

{"balances-and-info":{"on_hold":[],"available": {"USD":0.93033384},"usd_volume":"243.18","fee_bracket": {"maker":"0.00","taker":"0.60"},"global_usd_volume":"0.09942900"}}
I have this JSON response, and I'm trying to store it in an object, however as you can see "balances-and-info" cannot be used as a variable name. The method I have been using is:
RestClient client = new RestClient("http://currency-api.appspot.com/api/");
RestRequest request = new RestRequest(url);
var response = client.Execute<Currency>(request);
Currency obj = response.Data;
Where obviously the class is a lot easier
public class Currency
{
public string rate { get; set; }
}
So how can I handle this?
String.replace() balances-and-info with balances_and_info
in your code
YourObject deserialized = parseResponse(obj.replace("balances-and-info", "balances_and_info"));
YourObject parseResponse(string response) {
try
{
// https://www.nuget.org/packages/Newtonsoft.Json/
// Json.NET
YourObject ret = JsonConvert.DeserializeObject<YourObject>(response);
return ret;
}
catch (JsonSerializationException)
{
// do something
}
return null;
}
YourObject
Use http://json2csharp.com/ and generate your object (copy response string, replace balances-and-info with balances_and_info and generate)
public class Available
{
public double USD { get; set; }
}
public class FeeBracket
{
public string maker { get; set; }
public string taker { get; set; }
}
public class BalancesAndInfo
{
public List<object> on_hold { get; set; }
public Available available { get; set; }
public string usd_volume { get; set; }
public FeeBracket fee_bracket { get; set; }
public string global_usd_volume { get; set; }
}
public class YourObject
{
public BalancesAndInfo balances_and_info { get; set; }
}

Deserialising a json text file without json.net

I have some json data stored in a text file (the data is at https://github.com/VinceG/Auto-Cars-Makes-And-Models). I've run the json file through json2csharp which has generated the following classes for storage
public class Model
{
public string value { get; set; }
public string title { get; set; }
}
public class VehicleMake
{
public string value { get; set; }
public string title { get; set; }
public List<Model> models { get; set; }
}
I am trying to deserialise the data into the VehicleMake class using the following code
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Let's deserialise!");
var sb = new StringBuilder();
using (var sr = new StreamReader("models.json"))
{
string line;
while ((line = sr.ReadLine()) != null)
sb.AppendLine(line);
}
var vehicleList = Deserialize<VehicleMake>(sb.ToString());
Console.WriteLine("Done");
}
private static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
try
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception throw in Deserialize - {0}-{1}", ex.Message, ex.StackTrace);
return obj;
}
}
}
I've used this deserialize method in a number of different project and it has never caused an issue. Here though it is returning null into the vehicleList object.
The string builder.ToString() looks to contain all of the data (it is showing Other Yugo Models for the the final title which is correct)
I'm deliberately not using json.net as it's the only deserialisation of json I'm doing within this application and so it's somewhat overkill.
I should say that this isn't a homework project or anything like that
The json string represents an array, so you need to deserialize it to a List<VehicleMake>. Just change the following line:
var vehicleList = Deserialize<VehicleMake>(sb.ToString());
with:
var vehicleList = Deserialize<List<VehicleMake>>(sb.ToString());
You'll get a list of vehicles with properly initialized value, title and models properties.
You need to add [DataContract] and [DataMember] attributes to your class and members. Possibly also [Serializable]
using System;
using System.Runtime.Serialization;
[Serializable]
[DataContract]
public class Model
{
[DataMember(Name = "value")]
public string value { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
}
[Serializable]
[DataContract]
public class VehicleMake
{
[DataMember(Name = "value")]
public string value { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "models")]
public List<Model> models { get; set; }
}

Deserializing JSON with indexed array in c#

I'm very new to working with JSON and am dealing wtih a return from an API which I can't change the formatting of. The return example is : (actual urls have been removed)
{
"body":
{
"link":
{"linkurl": ["www.google.com"]}
},
"error": null,
"message": "Data Retrieved successfully",
"status": true
}
I am using the Newtonsoft.Json library with MVC 3, in VS2010.
My class is:
[JsonObject(MemberSerialization.OptIn)]
public class LinksJSON
{
[JsonProperty]
public string link{ get; set; }
[JsonProperty]
public string message { get; set; }
[JsonProperty]
public string error { get; set; }
[JsonProperty]
public bool status { get; set; }
}
I'm deserializing it with :
private static T _download_serialized_json_data<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
public string CheckJSONLink()
{
var url = "<api url-removed for security>";
var outObj = _download_serialized_json_data<LinksJSON>(url);
return outObj.Link;
}
However I'm trying to get the value of linkurl, which is an indexed array within Link.
How would I access this information?
You did not setup your class to match the JSON, your class says that link is a simple string, you your example shows it as a complex type.
In order to properly deserialize it as you expect, you will have to modify your class to match the JSON. Specifically link should be an instance of a class.
You should use the following classes:
[JsonObject(MemberSerialization.OptIn)]
public class LinksJSON
{
[JsonProperty]
public body body { get; set; }
[JsonProperty]
public string message { get; set; }
[JsonProperty]
public string error { get; set; }
[JsonProperty]
public bool status { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class body
{
[JsonProperty]
public link link { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class link
{
[JsonProperty]
public string[] linkurl { get; set; }
}

How to properly organize C# application design for muli-objects JSON?

I have problem with architectural problem for my C# application. I need to have the following JSON:
{data:{lat:22,lng:33}, error:{code:0,description:""}}
I'm trying to implement this JSON structure with these classes:
public class Response
{
public object Data { get; set; }
public object Error { get; set; }
public Response()
{
Error = new ErrorsManager();
}
}
public class Coordinates : Response
{
public double Lat { get; set; }
public double Lng { get; set; }
}
I can set values for Error without any problems. But how to set values for Data I can't understand. Can anybody suggest proper solution for this situation? I know that this problem can be solved with extends in Java. Can I use something similar in C#?
Update: I'd like to have common root objects in JSON - data and error. But data object can have different context like: coordinates, user data, etc.
You would set Data to an instance of coordinates. That is something like this:
public class Response
{
public object Data { get; set; }
public object Error { get; set; }
public Response()
{
Error = new ErrorsManager();
Data = new Coordinates();
}
}
public class Coordinates {
public double Lat { get; set; }
public double Lng { get; set; }
}
You might think about creating strongly typed versions of Response meaning something like this:
public class Response
{
public Coordinates Data { get; set; }
public ErrorsManager Error { get; set; }
public Response()
{
Error = new ErrorsManager();
Data = new Coordinates();
}
}
If you have different response types, you might want to have a base class defining only Error and the subclasses adding a new property. I assume you're using something like JSON.NET to serialize / deserialize.
You could be generic:
public class Response<T> where T : new() {
public T Data { get; set; }
public ErrorsManager Error { get; set; }
public Response() {
Error = new ErrorsManager();
Data = new T();
}
}
public class Coordinates {
/* left away */
}
Usage:
var response = new Response<Coordinates>();
response.Data.Lat = 0.01;
// whatever you like
Create type safe classes instead of declaring them as object
public class Response
{
public Coordinates Data { get; set; }
public Error Error { get; set; }
}
public class Error
{
public int code { get; set; }
public string description { get; set; }
}
public class Coordinates
{
public double Lat { get; set; }
public double Lng { get; set; }
}
You can deserialize the json string as
string jsonStr = #"{data:{lat:22,lng:33}, error:{code:0,description:""aaa""}}";
var jObj = JsonConvert.DeserializeObject<Response>(jsonStr); //Json.Net
or
var jObj2 = new JavaScriptSerializer().Deserialize<Response>(jsonStr);
You can also go totally dynamic way using Json.Net without declaring any of these classes
dynamic dynObj = JsonConvert.DeserializeObject(jsonStr);
Console.WriteLine(dynObj.data.lat);
Console.WriteLine(dynObj.error.description);
c#:
String JSON = (new JavaScriptSerializer()).Serialize(
new { data = new { lat = 22; lng = 33; }; error = new {code = 0; description=String.Empty;}; }
);
Or:
using System.Web.Script.Serialization;
public class myResponse
{
public Coordinates data;
public Error error;
public myResponse()
{
data = new Coordinates();
error = new Error();
}
}
public class Coordinates
{
public double lat;
public double lng;
}
public class Error
{
public int code;
public String description;
}
var resp = new myResponse();
resp.data.lat = 0.3453453453;
resp.data.lng = 0.3453453453;
resp.error.code = 0;
resp.error.description = "Description of error";
String JSON = (new JavaScriptSerializer()).Serialize(resp);

Categories

Resources