I have doubt about how creating a class for receiving the response from HttpWebResponse.
The code I use for receiving a json response is:
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
ResJson myojb = (ResJson )js.Deserialize(objText, typeof(ResJson ));
}
}
The json I receive is:
{
"name": "Rube Goldberg Machine Stage 1",
"published": true,
"description": "<p>.STEP Version\n<br /><br>Rube Goldberg Experiment</p>",
"raw_description": ".STEP Version\r\nhttp://grabcad.com/cadfiles/rube-goldberg-experiment",
"cached_slug": "rube-goldberg-machine-stage-1",
"created_at": "2011-04-06T21:58:06Z",
"updated_at": "2017-05-02T07:44:08Z",
"preview_image": "https://d2t1xqejof9utc.cloudfront.net/screenshots/pics/08d3763d43243a1a5f88c89dbfb8910c/card.jpg",
"image_missing_url": "https://d2t1xqejof9utc.cloudfront.net/screenshots/pics/missing_small.png",
"likes_count": 9,
"downloads_count": 116,
"comments_count": 1,
"contentfiles_count": 3,
"top_comments_count": 1,
"video_link": "https://youtu.be/paDE3KO7eb0",
"author": {
"name": "Scott Bruins",
"cached_slug": "scott.bruins",
"avatar": "https://d2t1xqejof9utc.cloudfront.net/members/avatars/320/feed.gif?1316795450"
},
"tags": [
"machine",
"rube",
"goldberg",
"crowdcad"
],
"softwares": [
{
"name": "Other",
"cached_slug": "other"
},
{
"name": "STL",
"cached_slug": "stl"
},
{
"name": "Rendering",
"cached_slug": "rendering"
}
]
}
When creating the ResJson class I can not figure out how set softwares variable type.
How should it be declared?
public class Software
{
[JsonProperty("name")]
public string Name {get;set;}
[JsonProperty("cached_slug")]
public string CachedSlug {get;set;}
}
And then in your ResJson:
{
...
[JsonProperty("softwares")]
public List<Software> Softwares {get;set;}
...
}
Related
I have a large json file and only want to use certain nested properties, here is the file
{
"type": "champion",
"format": "standAloneComplex",
"version": "6.24.1",
"data": {
"Aatrox": {
"version": "6.24.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"blurb": "Aatrox is a legendary warrior, one of only five that remain of an ancient race known as
the Darkin. He wields his massive blade with grace and poise, slicing through legions in a style
that is hypnotic to behold. With each foe felled, Aatrox's ...",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
"image": {
"full": "Aatrox.png",
"sprite": "champion0.png",
"group": "champion",
"x": 0,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Fighter",
"Tank"
],
},
"Ahri": {
"version": "6.24.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox",
"blurb": "Unlike other foxes that roamed the woods of southern Ionia, Ahri had always felt a
strange connection to the magical world around her; a connection that was somehow incomplete.
Deep inside, she felt the skin she had been born into was an ill fit for ...",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
"image": {
"full": "Ahri.png",
"sprite": "champion0.png",
"group": "champion",
"x": 48,
"y": 0,
"w": 48,
"h": 48
},
"tags": [
"Mage",
"Assassin"
],
},
It is a very long json file. I have a class that is
public class Champion
{
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set;}
}
public class ChampionRoot
{
public Dictionary<string, Champion> champions { get; set; }
}
What I am trying to do is start at the properties inside "Data" and only get "id", "key","name" and "title", and Deserialize those properties into my ChampionRoot class. I have searched and tried many things and cannot get it to work. Here is some of what I've tried in my controller
public IActionResult Champions()
{
var url = #"url.......";
WebClient client = new WebClient();
var download = client.DownloadString(url);
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(download);
return Json(champions); //This returns null in the view
}
I have also tried using JObject a few different ways and that doesn't work for me either
JObject obj = JObject.Parse(download);
var json = obj["key"]["id"]["name"]["title"]; //throws object reference error
Then I've tried this
JObject obj = JObject.Parse(download);
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(obj.ToString());
//This also returns null in the view
I have searched and read many answers but I cannot figure it out. The question is how can I only Deserialize those 4 nested properties into an object? The url is http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json for full json file.
You can use Dictionary<string, Champion> for data property:
public class ChampionRoot
{
public Dictionary<string,Champion> data { get; set; }
}
var champions = Newtonsoft.Json.JsonConvert.DeserializeObject<ChampionRoot>(download);
I am new to C# and I have a certain JSON format that I am trying to read. I have managed to bring in the whole string but I only need the "data" bit.
{
"notes": {
"status": "success",
"datasource": "Internet",
"result_rows": 35
},
"data": [
["Date", "Visits", "Pageviews", "Clicks", "Bounces", "Time on Website"],
["2018-10-01", 57, 145, 39, 16, 4112],
["2017-10-02", 32, 29, 34, 29, 89],
["2019-10-03", 40, 129, 18, 35, 122216],
["2016-12-04", 15, 12, 13, 10, 14408],
["2019-01-08", 13, 23, 110, 72, 12277],
["2011-12-06", 45, 44, 33, 5, 33784],
["2018-06-15", 30, 428, 454, 64, 67319],
"columns": [{
"name": "Date",
"field": "date",
"type": "dim",
"data_type": "string.time.date"
},
{
"name": "Visits",
"field": "visits",
"type": "met",
"data_type": "int.number.value"
},
{
"name": "Pageviews",
"field": "pageviews",
"type": "met",
"data_type": "int.number.value"
},
{
"name": "Clicks",
"field": "clicks",
"type": "met",
"data_type": "int.number.value"
},
{
"name": "Bounces",
"field": "bounces",
"type": "met",
"data_type": "int.number.value"
},
{
"name": "Time on Website",
"field": "websiteduration",
"type": "met",
"data_type": "float.number.value"
}
]
}
My code fails at:
List<item> Data = JsonConvert.DeserializeObject<List<item>>(jsonString);
I am not too sure how to only extract the data bit in a proper format. Thank you in advance
The code that i am using currently
namespace API
{
public class item
{
public string Date { get; set; }
public string Visits { get; set; }
public string Pageviews { get; set; }
public string Clicks{get; set;}
public string Bounces { get; set; }
[JsonProperty("Time on website")]
public string Time_on_Website { get; set; }
}
}
namespace API
{
public class Program
{
public static void Main(string[] args)
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://website.com"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<item> Data = JsonConvert.DeserializeObject<List<item>>(jsonString);
Console.WriteLine(Data);
}
}
}
i think firstly you should add a class like this
public class Items
{
public List<Item> data { get; set; }
}
and then
Items items = new JavaScriptSerializer().Deserialize<Items>(jsonString);
foreach (var item in items.data)
{
...
...
}
but i think your json string is in an invalid format.
I make an API call to a URL using C# and it returns JSon response and i download the json file.
i would like to write the json data to database for use by a web application.
how can i import the json file into sql or write it direct from my c# program to db . am using sql 2016
My JSon file looks as follows :
{
"Items": [
{
"LocalTimestamp": "2017-07-05T18:59:29+02:00",
"Id": 653914348,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.90225,
-26.07706
]
},
{
"LocalTimestamp": "2017-07-05T08:41:08+02:00",
"Id": 653709051,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.90229,
-26.07753
]
},
{
"LocalTimestamp": "2017-07-05T07:42:19+02:00",
"Id": 653692142,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.90228,
-26.07708
]
},
{
"LocalTimestamp": "2017-07-05T07:21:47+02:00",
"Id": 653683088,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.9222,
-26.04318
]
},
{
"LocalTimestamp": "2017-07-05T07:21:00+02:00",
"Id": 653682830,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.92348,
-26.04612
]
},
{
"LocalTimestamp": "2017-07-04T10:15:35+02:00",
"Id": 653330923,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.997,
-26.05747
]
},
{
"LocalTimestamp": "2017-07-04T09:41:19+02:00",
"Id": 653320268,
"Description": "Trip Startup",
"Processed": false,
"Position": [
28.02899,
-26.20546
]
},
{
"LocalTimestamp": "2017-07-04T09:32:54+02:00",
"Id": 653317769,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
28.0293,
-26.20549
]
},
{
"LocalTimestamp": "2017-07-03T18:40:43+02:00",
"Id": 653089737,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.90228,
-26.07707
]
},
{
"LocalTimestamp": "2017-07-03T18:29:01+02:00",
"Id": 653086470,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.94599,
-26.07828
]
},
{
"LocalTimestamp": "2017-07-03T18:26:30+02:00",
"Id": 653085810,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.94662,
-26.07807
]
},
{
"LocalTimestamp": "2017-07-03T18:15:50+02:00",
"Id": 653082613,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.98847,
-26.05269
]
},
{
"LocalTimestamp": "2017-07-03T18:13:15+02:00",
"Id": 653082018,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.99036,
-26.05341
]
}
],
"HasMoreResults": false
}
Ok. As i have mentioned in my comment, you have to de-serialize the json string which you received to object/class and save that class/object properties to database using c#.
In database, you need to create tables based on your "json string structure" or "class/object".
According to your json string the class should be like below
public class Item
{
public string LocalTimestamp { get; set; }
public int Id { get; set; }
public string Description { get; set; }
public bool Processed { get; set; }
public List<double> Position { get; set; }
}
public class AllItems
{
public List<Item> Items { get; set; }
public bool HasMoreResults { get; set; }
}
To de-serialize the json string, below is the code and for that, you need the namespace "System.Web.Script.Serialization".
string jsonstring = #"define your json string here";
//Deserialize the json string to the object/class format
var serializer = new JavaScriptSerializer();
AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
Create your database table as per the json string structure
CREATE TABLE AllItemsTable (
ItemIdPrimary int NOT NULL IDENTITY(1,1),
LocalTimestamp nvarchar(255),
Id int,
Description nvarchar(255),
Processed nvarchar(255),
Position1 nvarchar(50),
Position2 nvarchar(50)
PRIMARY KEY (ItemIdPrimary)
);
Here the complete code to de-serialize the json string and save data
to database.
For jsonstring, i have added a json file named as "test1.json" inside
the application and copied your json string to the json file.Late i am
consuming the json from that file("test1.json")
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Configuration;
namespace DeserializeJson2ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//Get the Json string
string jsonstring = File.ReadAllText(#"D:\My Apps\Console Applications\DeserializeJson2ConsoleApp\DeserializeJson2ConsoleApp\test1.json");
//Deserialize the json string to the object/class format
var serializer = new JavaScriptSerializer();
AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
//Save the deserilized object/class to database
//Get your connection string defined inside the Web.config(for web application) / App.config(for console/windows/wpf/classlibrary application) file
string myConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
//Create your Sql Connection here
using (SqlConnection con = new SqlConnection(myConnectionString))
{
//Open the sql connection
con.Open();
//Loop each items and save to database
foreach (var item in allItemsObj.Items)
{
//Save/Insert to database
if(SaveToDatabase(con, item))
{
Console.WriteLine("Success : " + item.Description + " Saved into database");
}
else
{
Console.WriteLine("Error : " + item.Description + " unable to Saved into database");
}
}
}
Console.Read();
}
/// <summary>
/// Insert to database
/// </summary>
/// <param name="con"></param>
/// <param name="aItemObj"></param>
/// <returns></returns>
static bool SaveToDatabase(SqlConnection con,Item aItemObj)
{
try
{
string insertQuery = #"Insert into AllItemsTable(LocalTimestamp,Id,Description,Processed,Position1,Position2) Values(#LocalTimestamp,#Id,#Description,#Processed,#Position1,#Position2)";
using (SqlCommand cmd = new SqlCommand(insertQuery, con))
{
cmd.Parameters.Add(new SqlParameter("#LocalTimestamp",aItemObj.LocalTimestamp));
cmd.Parameters.Add(new SqlParameter("#Id", aItemObj.Id));
cmd.Parameters.Add(new SqlParameter("#Description", aItemObj.Description));
cmd.Parameters.Add(new SqlParameter("#Processed", aItemObj.Processed));
for(int index=0;index<aItemObj.Position.Count;index++)
{
if(index==0)
cmd.Parameters.Add(new SqlParameter("#Position1", aItemObj.Position[index].ToString()));
else
cmd.Parameters.Add(new SqlParameter("#Position2", aItemObj.Position[index].ToString()));
}
cmd.ExecuteNonQuery();
}
return true;
}
catch (Exception objEx)
{
return false;
}
}
}
public class Item
{
public string LocalTimestamp { get; set; }
public int Id { get; set; }
public string Description { get; set; }
public bool Processed { get; set; }
public List<double> Position { get; set; }
}
public class AllItems
{
public List<Item> Items { get; set; }
public bool HasMoreResults { get; set; }
}
}
And here is the message in console after data saved to the database.
And here is the data which has been saved to the database.
Hope, it solves your problem. Revert me back if you have any issues.
Hi I would like to use the json collection from the code below in an angular repeater.
I need to give the collection a name but i dont know how
this is the code to generate the JSON
public JsonResult GetProducts()
{
var result = db.Products.ToList();
var list = JsonConvert.SerializeObject(result, Formatting.None, new JsonSerializerSettings(){ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore});
return Json(list,JsonRequestBehavior.AllowGet);
}
and this is the result
[{
"Category": {
"ID": 4,
"Name": "TEST"
},
"OrderDetails": [],
"ID": 10006,
"Description": "TEST",
"Name": "TEST",
"Price": 3.20,
"PictureUrl":"",
"CategoryId": 4,
"AddedToShop": "2016-12-11T14:52:57.677"
},
{
"Category": {
"ID": 4,
"Name": "TEST"
},
"OrderDetails": [],
"ID": 20005,
"Description": "TEST2",
"Name": "TEST2",
"Price": 3.20,
"PictureUrl":"",
"CategoryId": 4,
"AddedToShop": "2016-12-12T12:02:10.593"
}]
and I would like it to be like the code below so I can use the products tag to iterate .
{
"products": [{
"Category": {
"ID": 4,
"Name": "TEST"
},
"OrderDetails": [],
"ID": 10006,
"Description": "TEST",
"Name": "TEST",
"Price": 3.20,
"PictureUrl":"",
"CategoryId": 4,
"AddedToShop": "2016-12-11T14:52:57.677"
},
{
"Category": {
"ID": 4,
"Name": "TEST"
},
"OrderDetails": [],
"ID": 20005,
"Description": "TEST2",
"Name": "TEST2",
"Price": 3.20,
"PictureUrl":"",
"CategoryId": 4,
"AddedToShop": "2016-12-12T12:02:10.593"
}]}
If you are using WebAPI controllers you don't need to send JsonResult, all you need to do is create a class and send it back to client:
public class MyClass
{
public List<Product> Products { get; set; }
}
And in your controller:
public MyClass Get() {
return new MyClass {
Products = db.Products.ToList()
};
}
OR:
Simply create your object and then pass it in the serializer:
JsonConvert.SerializeObject( { "products": result }, Formatting.None, new JsonSerializerSettings(){ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore})
You can use
var list = JsonConvert.SerializeObject(new { products = result }, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore });
One solution for your problem is, define a seperate class and define a property for that class as either a collection or list of the type "db.Products"(Use the appropriate class name for this object as you have in your code) and when you serialize that object you will get it as you have asked for
class ProductList
{
public Collection<YourType> Products{get; set;}
}
OR
class ProductList
{
public List<YourType> Products{get; set;}
}
I'm trying to Deserialize object to list of object using JSON.NET lib. My json file is:
[
{
"id": 1,
"name": "Poczta",
"description": "Opis",
"latitude": 52.25197,
"longitude": 20.896355,
"accuracy": 0,
"type": "",
"image": null
},
{
"id": 2,
"name": "WAT",
"description": "Budynek główny - sztab.\r\nzażółć gęślą jaźń",
"latitude": 52.2531213,
"longitude": 20.8995849,
"accuracy": 0,
"type": "Uczelnia",
"image": null
},
{
"id": 3,
"name": "Przychodnia",
"description": "Opis",
"latitude": 52.250808,
"longitude": 20.895348,
"accuracy": 0,
"type": "",
"image": null
},
{
"id": 4,
"name": "DS3",
"description": "Opis",
"latitude": 52.250063,
"longitude": 20.895847,
"accuracy": 0,
"type": "",
"image": null
},
{
"id": 5,
"name": "DS2",
"description": "Opis",
"latitude": 52.2497674,
"longitude": 20.8966583,
"accuracy": 0,
"type": "",
"image": null
},
{
"id": 6,
"name": "DS1",
"description": "Opis",
"latitude": 52.25088,
"longitude": 20.897492,
"accuracy": 0,
"type": "",
"image": null
},
{
"id": 7,
"name": "DS4",
"description": "To jest opis",
"latitude": 52.2539982,
"longitude": 20.8971716,
"accuracy": 0,
"type": "",
"image": null
},
{
"id": 15,
"name": "a",
"description": "b",
"latitude": 52.250105,
"longitude": 20.896124,
"accuracy": 0,
"type": "Uczelnia",
"image": null
}
]
And I wrote some code to do that, but it doesn't work. I tried many options like dynamic deserialize and now i'm tried to make a list.
async private void webServiceGetPoints()
{
try
{
var client = new HttpClient();
var response = await client.GetAsync(new Uri("\\private\\"));
var result = await response.Content.ReadAsStringAsync();
List<WebServiceTag> convert = JsonConvert.DeserializeObject<List<WebServiceTag>>(result) as List<WebServiceTag>;
Debug.WriteLine(convert.Count);
}
catch (JsonSerializationException jsonerr)
{
Debug.WriteLine(jsonerr.ToString());
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
This code based on my own class with is:
class WebServiceTag
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("description")]
public string description { get; set; }
[JsonProperty("latitude")]
public double latitude { get; set; }
[JsonProperty("longitude")]
public double longitude { get; set; }
[JsonProperty("accuracy")]
public int accuracy { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("image")]
public string image { get; set; }
}
I found that trying to use:
JsonConvert.DeserializeObject<List<T>>()
wouldn't work for me. I found that this worked instead.
JsonConvert.DeserializeObject<IEnumerable<T>>()
Hope its a better late than never answer.
If work for u... like it
List<modelCasa> objList = JsonConvert.DeserializeObject<List<modelCasa>>(json);
Response Body Class>>>
public class RestResponse
{
public string status { get; set; }
}
post Body Class>>>
class Customer_List
{
public string phone { get; set; }
}
in Void >>>>
Customer_List send= new Customer_List
{
phone= "***"
};
//
string json = JsonConvert.SerializeObject(send);
//
var client = new RestClient("http://localhost:1959/***");
var request = new RestRequest();
//
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", json,
ParameterType.RequestBody);
//
var response = client.Execute(request);
var content = response.Content;
it's answer for me !
var resp = JsonConvert.DeserializeObject<List<RestResponse>>(content);