Return Json Format to View - MVC - json

I am new to asp.net MVC. I hav to return Json from controller to view using ajax call, that is perfect.
I want to return below json format to view.
[{
"name": "A",
"data": [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] },
{
"name": "B",
"data": [3.9, 2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
},
{
"name": "C",
"data": [3.9, 2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
I have tried below modal to return such a format,
public class myModel
{
public List<string> Name { get; set; }
public List<float> Average { get; set; }
}
What should be my model like to return above mentioned format?

MyModel should be modified like this
public class MyModel
{
public string name { get; set; }
public List<float> data { get; set; }
}
as name property is only for a single string, and data is actually the array holding the float values.
You can return List<MyModel> or array - MyModel[] as JSON from ajax call

model type should be:
public class myModel
{
public string name { get; set; }
public List<float> data { get; set; }
}
AND in Controller:
List<myModel> list=new List<myModel>();
return new JsonResult()
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = Int32.MaxValue
};

public class MyModel
{
public string Name { get; set; }
public List<float> Data { get; set; }
}
public JsonResult MyMethod()
{
List<MyModel> list = new List<MyModel>();
// Do stuff
return Json(list);
}

Viewmodel:
public class ViewModel
{
public List<MyModel> myModel {get;set;}
}
myModel should be like this:
public class myModel
{
public string name { get; set; }
public IList<double> data { get; set; }
}
You can easily generate this kind of task with jsonutils online.

Your model should be like this.
public class myModel
{
public string name { get; set; }
public List<double> data { get; set; }
}
Here name contain single string value and data is contain array of double value.
Note : Use json2charp to convert your JSON to c# class type or if you are using vs2013 or above version paste copied JSON in C# class type.

Related

Deserialize JSON string embedded within JSON directly

I'm using .netcore 3.1 and I'm using System.Text.Json for serialization and deserialization. I didn't know how to phrase my question precisely. I looked around but couldn't find a direct answer for my question.
Apologies if it's a duplicate.
This is a sample JSON response.
{
"properties": {
"subscriptionId": "sub1",
"usageStartTime": "2015-03-03T00:00:00+00:00",
"usageEndTime": "2015-03-04T00:00:00+00:00",
"instanceData": "{\"Microsoft.Resources\":{\"resourceUri\":\"resourceUri1\",\"location\":\"Alaska\",\"tags\":null,\"additionalInfo\":null}}",
"quantity": 2.4000000000,
"meterId": "meterID1"
}
}
I'm interested in directly parsing instanceData.
If you observe closely, instanceData is an embedded JSON string.
{
"Microsoft.Resources": {
"resourceUri": "resourceUri1",
"location": "Alaska",
"tags": null,
"additionalInfo": null
}
}
Question:
Is it possible to parse this instanceData while the whole Json is being parsed? Can we add some Attributes to instanceData field for direct parsing? Right now, I'm accessing the string from the parsed model class and parsing instanceData separately.
This is what I'm doing right now (something like this):
JsonSerializer.Deserialize<MicrosoftResources>(parsedResponse.instanceData).
I have already built model classes for instanceData and other entities. Currently, instanceData is of type string in my root model class.
I'm interested in directly parsing instanceData. If you observe closely, instanceData is an embedded JSON string
Is it possible to parse this instanceData while the whole Json is being parsed?
You can achieve above requirement by creating and using a custom converter, like below.
public class ResConverter : JsonConverter<InstanceData>
{
public override InstanceData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
//you can implement it based on your actual requirement
//...
string jsonData = reader.GetString();
var instanceData = System.Text.Json.JsonSerializer.Deserialize<InstanceData>(jsonData);
return instanceData;
}
Model Classes
public class MyModel
{
public Properties Properties { get; set; }
}
public class Properties
{
public string SubscriptionId { get; set; }
public DateTimeOffset UsageStartTime { get; set; }
public DateTimeOffset UsageEndTime { get; set; }
[JsonConverter(typeof(ResConverter))]
public InstanceData InstanceData { get; set; }
public double Quantity { get; set; }
public string MeterId { get; set; }
}
public class InstanceData
{
[JsonPropertyName("Microsoft.Resources")]
public MicrosoftResources MicrosoftResources { get; set; }
}
public class MicrosoftResources
{
public string ResourceUri { get; set; }
public string Location { get; set; }
public object Tags { get; set; }
public object AdditionalInfo { get; set; }
}
Test code and result
var jsondata = "{\"Properties\":{\"SubscriptionId\":\"sub1\",\"UsageStartTime\":\"2015-03-03T00:00:00+00:00\",\"UsageEndTime\":\"2015-03-04T00:00:00+00:00\",\"InstanceData\":\"{\\u0022Microsoft.Resources\\u0022:{\\u0022ResourceUri\\u0022:\\u0022resourceUri1\\u0022,\\u0022Location\\u0022:\\u0022Alaska\\u0022,\\u0022Tags\\u0022:null,\\u0022AdditionalInfo\\u0022:null}}\",\"Quantity\":2.4,\"MeterId\":\"meterID1\"}}";
MyModel myModel = System.Text.Json.JsonSerializer.Deserialize<MyModel>(jsondata);
If you can change the instanceData to Json instead of string like this.
{
"properties": {
"subscriptionId": "sub1",
"usageStartTime": "2015-03-03T00:00:00+00:00",
"usageEndTime": "2015-03-04T00:00:00+00:00",
"instanceData": {"Microsoft.Resources":{"resourceUri":"resourceUri1","location":"Alaska","tags":null,"additionalInfo":null}},
"quantity": 2.4000000000,
"meterId": "meterID1"
}
}
You can easily deserialize your Json using the example below.
Model Classes:
public partial class Properties
{
[JsonPropertyName("properties")]
public PropertiesClass PropertiesProperties { get; set; }
}
public partial class PropertiesClass
{
[JsonPropertyName("subscriptionId")]
public string SubscriptionId { get; set; }
[JsonPropertyName("usageStartTime")]
public DateTimeOffset UsageStartTime { get; set; }
[JsonPropertyName("usageEndTime")]
public DateTimeOffset UsageEndTime { get; set; }
[JsonPropertyName("instanceData")]
public InstanceData InstanceData { get; set; }
[JsonPropertyName("quantity")]
public double Quantity { get; set; }
[JsonPropertyName("meterId")]
public string MeterId { get; set; }
}
public partial class InstanceData
{
[JsonPropertyName("Microsoft.Resources")]
public MicrosoftResources MicrosoftResources { get; set; }
}
public partial class MicrosoftResources
{
[JsonPropertyName("resourceUri")]
public string ResourceUri { get; set; }
[JsonPropertyName("location")]
public string Location { get; set; }
[JsonPropertyName("tags")]
public object Tags { get; set; }
[JsonPropertyName("additionalInfo")]
public object AdditionalInfo { get; set; }
}
Usage:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Program
{
static void Main(string[] args)
{
// escaped version, just for demo
var json =
"{\r\n \"properties\": {\r\n \"subscriptionId\": \"sub1\",\r\n \"usageStartTime\": \"2015-03-03T00:00:00+00:00\",\r\n \"usageEndTime\": \"2015-03-04T00:00:00+00:00\",\r\n \"instanceData\": {\"Microsoft.Resources\":{\"resourceUri\":\"resourceUri1\",\"location\":\"Alaska\",\"tags\":null,\"additionalInfo\":null}},\r\n \"quantity\": 2.4000000000,\r\n \"meterId\": \"meterID1\"\r\n }\r\n}";
var props = JsonSerializer.Deserialize<Properties>(json);
}
}
Props will have all of the data. I hope this helps.

Deserialize complex json in C#

I have this json and need to parse the nested details. using Newtonsoft.Json for Deserializing but cant really parse this complex json.
{
"name": "John",
"email": "john#gmail.com",
"data": [
{
"company_name": "instagram",
"company_email": "abc#email.com",
"org": {
"org_name": "john-insta",
"org_dob": "1/1/1990",
}
},
{
"company_name": "google",
"company_email": "abc1#email.com",
"org": {
"org_name": "john-google",
"org_dob": "1/1/1990",
}
},
]
The number of entries in "data" may actually be varying dynamically, how do I parse the entries for company_name, company_email, org_name,org_dob.
What is the problem you are having? This seems fairly simple JSON array. Setup your classes like this.
public class MyClass
{
public string name { get; set; }
public string email { get; set; }
public List<DataClass> data { get; set; }
}
public class DataClass
{
public string company_name { get; set; }
public string company_email { get; set; }
public Org org { get; set; }
//Any other and all possible properties...
}
public class Org
{
public string org_name { get; set; }
public string org_dob { get; set; }
}
Then it can be parsed using Newtonsoft or similar using.
var test = JsonConvert.DeserializeObject<MyClass>(json);
This method also has an overload where you can pass settings to ignore nulls.
var test = JsonConvert.DeserializeObject<MyClass>(json,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

JSON DeserializeObject Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

When I deserialize JSON to my class using Newtonsoft JSON.net, I get this error. What could be the cause of it ? Certainly I am missing something obvious..
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
Here is my JSON:
[
{
"AgreementUID": "a8ea9f59-82f3-4799-b684-06a2cd95d9a1",
"ProjectUID": "851D12CE-7DC3-E511-9C58-F0DEF17C096F",
"year": "2016",
"data": [
{
"month": 1,
"B": "4",
"P": "1",
"F": "1"
},
{
"month": 2,
"B": "",
"P": "",
"F": ""
}
]
}
]
Here is my Class:
public class AgreementBreakdownObject
{
public string AgreementUID { get; set; }
public string ProjectUID { get; set; }
public string year { get; set; }
public List<AgreementBreakdownDataObject> data { get; set; }
}
public class AgreementBreakdownDataObject
{
public int month { get; set; }
public string B { get; set; }
public string P { get; set; }
public string F { get; set; }
}
I do deserialize like this:
string jsonData = hData.Value;
var data = JsonConvert.DeserializeObject<List<AgreementBreakdownObject>> (jsonData);
Please suggest what is my mistake here. thank you
You'll need to escape your quotes if the json is within a C# string. Example below:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApp3
{
public class AgreementBreakdownObject
{
public string AgreementUID { get; set; }
public string ProjectUID { get; set; }
public string year { get; set; }
public List<AgreementBreakdownDataObject> data { get; set; }
}
public class AgreementBreakdownDataObject
{
public int month { get; set; }
public string B { get; set; }
public string P { get; set; }
public string F { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = JsonConvert.DeserializeObject<List<AgreementBreakdownObject>>(#"[
{
""AgreementUID"": ""a8ea9f59-82f3-4799-b684-06a2cd95d9a1"",
""ProjectUID"": ""851D12CE-7DC3-E511-9C58-F0DEF17C096F"",
""year"": ""2016"",
""data"": [
{
""month"": 1,
""B"": ""4"",
""P"": ""1"",
""F"": ""1""
},
{
""month"": 2,
""B"": """",
""P"": """",
""F"": """"
}
]
}
]");
Console.WriteLine(JsonConvert.SerializeObject(data, Formatting.Indented));
Console.ReadKey();
}
}
}
Relevant excerpt from MSDN:
Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string.

Fetch JSON array using WebClient and Json.Net and display it in textview?

My Activity code is:
private void MClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
string json = Encoding.UTF8.GetString(e.Result);
var Details = JsonConvert.DeserializeObject(json);
}
My doctor.cs class code is:
namespace App12
{
public class Doctor
{
public string DoctorId { get; set; }
public string doctorName { get; set; }
public string specialityId { get; set; }
public string experiance { get; set; }
public string fee { get; set; }
}
public class RootObject
{
public Doctor doctor { get; set; }
}
}
JSON array is:
{
"0": {
"DoctorId": "1",
"doctorName": "DR.Rama",
"specialityId": "1",
"experiance": "5 years",
"fee": "300rs"
}
}
I am trying to show this in textview but it gives me an error:
System.InvalidCastException: Specified cast is not valid.
You have two problems here.
Your class structure doesn't quite match up with the shape of the JSON data. This JSON isn't technically an array either; it's a dictionary. You need to deserialize into a Dictionary<string, Doctor>.
When calling JsonConvert.DeserializeObject you need to specify a type parameter. If you don't, the return type will be JObject. This may be the cause of the InvalidCastException.
Try it like this:
var dict = JsonConvert.DeserializeObject<Dictionary<string, Doctor>>(json);
From there you can loop through the doctors like this:
foreach (var doctor in dict.Values)
{
textView.Append(doctor.doctorName);
}

How to get a json string using rest api for windows phone?

My Json is of the following format.
{
"code" : o,
"message" : "success",
"book_list":
[
{"name": "C","price":180},
{"name": "C++","price":180},
{"name": "C#","price":180},
]
}
I am a brand new beginner to Windows phone app development!!
How shall i get list of books from the url and store it in a dictionary kind of thing??(i.e as a key value pair) for windows phone 7??
You can use this JSON framework for .NET:
using System.Runtime.Serialization;
[DataContract]
public class BookShop
{
[DataMember(Name = "code")]
public int Code { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "book_list")]
public List<Book> Result { get; set; }
}
[DataContract]
public class Book
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "price")]
public int Price { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
string json = "{\"code\": 0,\"message\": \"success\",\"book_list\": [{\"name\": \"C\",\"price\": 180}, {\"name\": \"C++\",\"price\": 180 }, {\"name\": \"C#\",\"price\": 180}]}";
var myObjects = JsonConvert.DeserializeObject<BookShop>(json);
foreach (var item in myObjects.Result)
{
Debug.WriteLine("{0} has price {1}", item.Name, item.Price);
}
}
}