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.
Related
I have created web api in asp.net mvc where I am calling usp_JsonPract this SP which is returning JSON string from DB, Now I am facing problem to convert this string on .net mvc web api.
My stored procedure code:
Create proc [dbo].[usp_JsonPract]
as
BeginSelect category title
,[data] = JSON_QUERY(
(
select din.dishId,din.dishName,din.dishPrice,din.dishImage, din.dishType,
JSON_QUERY(dishPriceAndSize, '$.dishPriceAndSize') AS dishPriceAndSize,
JSON_QUERY(JAddOns, '$.addOns') AS addOns,
din.includedEggs, din.dishDescription, din.rating, din.review,din.discount
from DishMaster din
where din.category = dout.category
--and dishId in ( 11, 12,13 , 7 )
for json path
,INCLUDE_NULL_VALUES
)
)from DishMaster dout
group by category
for json path,without_array_wrapper
Stored procedure is returing JSON string that I want to pass to the client. I am using JsonConvert.DeserializeObject(jsonstr); to convert.
My C# code:
public object SQLJSONPract()
{
string jsonstr = string.Empty;
object o;
try
{
cmd.CommandText = "usp_JsonPract";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
var d = ds.Tables[0].Rows[0][0];
jsonstr = d.ToString();
object a = JsonConvert.DeserializeObject(jsonstr);
return (object)a;
}
catch (Exception ex)
{
return ex.Message;
}
}
Gives exception as below:
"Unterminated string. Expected delimiter: ". Path 'userDetails[2].data[1].addOns[1].name', line 59, position 3."
Result sample JSON is like this:
{
"title": "Rice",
"data": [
{
"dishId": 11,
"dishName": "stream rice",
"dishPrice": 40.0,
"dishImage": "streamrice.jpg",
"dishType": "VEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "stream rice is delicious in test",
"rating": 4.5,
"review": "GOOD",
"discount": 20
},
{
"dishId": 12,
"dishName": "stream rice",
"dishPrice": 40.0,
"dishImage": "streamrice.jpg",
"dishType": "VEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "stream rice is delicious in test",
"rating": 4.5,
"review": "GOOD",
"discount": 20
},
{
"dishId": 13,
"dishName": "stream rice",
"dishPrice": 40.0,
"dishImage": "streamrice.jpg",
"dishType": "VEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "stream rice is delicious in test",
"rating": 4.5,
"review": "GOOD",
"discount": 20
},
{
"dishId": 7,
"dishName": "Chicken Biryani",
"dishPrice": 160.0,
"dishImage": "ChickenBiryani.jpg",
"dishType": "NonVEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "Special Chicken Biryani For Our Valued Guest",
"rating": 4.5,
"review": "GOOD",
"discount": 20
}
]}
If any other suggestion for achieving this. Kindly suggest.
Make a file called JsonPract.cs and paste the following classes, in order to create several class that can be mapped to the json that you post in the question:
public class JsonPract
{
public string title { get; set; }
public List<Datum> data { get; set; }
}
public class DishPriceAndSize
{
public string size { get; set; }
public int price { get; set; }
}
public class AddOn
{
public string name { get; set; }
public int price { get; set; }
}
public class Datum
{
public int dishId { get; set; }
public string dishName { get; set; }
public double dishPrice { get; set; }
public string dishImage { get; set; }
public string dishType { get; set; }
public List<DishPriceAndSize> dishPriceAndSize { get; set; }
public List<AddOn> addOns { get; set; }
public bool includedEggs { get; set; }
public string dishDescription { get; set; }
public double rating { get; set; }
public string review { get; set; }
public int discount { get; set; }
}
Then you can deserialize your object as:
JsonPract myDeserializedClass = JsonConvert.DeserializeObject<JsonPract>(myJsonResponse);
For example:
public JsonPract SQLJSONPract()
{
string jsonstr = string.Empty;
object o;
try
{
cmd.CommandText = "usp_JsonPract";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
var d = ds.Tables[0].Rows[0][0];
jsonstr = d.ToString();
JsonPract a = JsonConvert.DeserializeObject<JsonPract>(jsonstr);
return a;
}
catch (Exception ex)
{
throw ex;
}
}
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;}
...
}
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);
i am getting measurements from withings and want to show them in graphs but not able to convert it to json. i also try JsonConvert.SerializeObject(myString) using Newtonsoft.dlland simple
System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer();
sr.Serialize(myString);
but it is not converting.
My withings measurement string is as follows.
{
"status": 0,
"body": {
"updatetime": 1392764547,
"measuregrps": [
{
"grpid": 17945868,
"attrib": 0,
"date": 139984270,
"category": 1,
"measures": [
{
"value": 72,
"type": 9,
"unit": 0
},
{
"value": 152,
"type": 10,
"unit": 7
},
{
"value": 87,
"type": 17,
"unit": 0
}
]
},
{
"grpid": 176587495,
"attrib": 0,
"date": 13915689,
"category": 1,
"measures": [
{
"value": 94,
"type": 9,
"unit": 0
},
{
"value": 145,
"type": 10,
"unit": 0
},
{
"value": 109,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179262494,
"attrib": 0,
"date": 1391369607,
"category": 1,
"measures": [
{
"value": 77,
"type": 9,
"unit": 0
},
{
"value": 121,
"type": 10,
"unit": 0
},
{
"value": 87,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179258492,
"attrib": 0,
"date": 1391171167,
"category": 1,
"measures": [
{
"value": 61,
"type": 9,
"unit": 0
},
{
"value": 107,
"type": 10,
"unit": 0
},
{
"value": 80,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179089150,
"attrib": 0,
"date": 1391167537,
"category": 1,
"measures": [
{
"value": 69,
"type": 9,
"unit": 0
},
{
"value": 112,
"type": 10,
"unit": 0
},
{
"value": 67,
"type": 11,
"unit": 0
}
]
},
{
"grpid": 179079661,
"attrib": 2,
"date": 1391164672,
"category": 1,
"measures": [
{
"value": 720,
"type": 1,
"unit": -1
}
]
},
{
"grpid": 17998560,
"attrib": 2,
"date": 146989672,
"category": 1,
"measures": [
{
"value": 284,
"type": 4,
"unit": -2
}
]
}
]
}
}
It seems, you want to deserialize your json string, not serialize:
var obj = JsonConvert.DeserializeObject<Withings.RootObject>(json);
public class Withings
{
public class Measure
{
public int value { get; set; }
public int type { get; set; }
public int unit { get; set; }
}
public class Measuregrp
{
public int grpid { get; set; }
public int attrib { get; set; }
public int date { get; set; }
public int category { get; set; }
public List<Measure> measures { get; set; }
}
public class Body
{
public int updatetime { get; set; }
public List<Measuregrp> measuregrps { get; set; }
}
public class RootObject
{
public int status { get; set; }
public Body body { get; set; }
}
}
JsonConvert.SerializeObject(myString) takes an object an returns a string. If you want to turn a string into an object you want to use Deserialize<T>(sting json). Given the arguments name in your sample is myString I would assume you're using the method wrong.
To deserialize you need an equivalent type like;
public class myObject
{
public int status { get; set; }
public Body body { get; set; }
}
public class Body
{
//other parameters ect
}
Your object model needs to exactly match the json in order by Deserialize<T> to behave correctly.
First: I'm new to using JSON, and I used the answers on here to use Json.Net to deserialize data from a Pokemon API into a C# class (Pokemon class). I used http://json2csharp.com to help me define my class and it looks like this:
public class Pokemon
{
public Pokemon(string json)
{
JsonConvert.PopulateObject(json, this, PokeApi.JsonSerializerSettings);
}
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("evolutions")]
public Evolutions evolutions { get; set; }
[JsonProperty("national_id")]
public int national_id { get; set; }
}
with a bunch of other properties like resource_uri, attack stat, etc.
As the answer offered on the aforementioned link said, I used JsonConvert.DeserializeObject(json) like so:
public Pokemon GetPokemon(int nationalId)
{
using (WebClient client = new WebClient())
{
var json = client.DownloadString("http://pokeapi.co/api/v1/pokemon/" + nationalId + "/");
var output = JsonConvert.DeserializeObject<Pokemon>(json);
return output;
}
}
However I keep getting an exception that says "Cannot deserialize the current JSON array (e.g.[1,2,3]) into type 'Evolutions' because the type requires a JSON object..."
I found a lot of other questions asking the same exact thing, but I was confused with the top answers - sometimes the answer was to use JsonProperty, sometimes it was to use JsonConverter, without really an explanation on what all these meant. Do I need both?
Edit: sample json (call: http://pokeapi.co/api/v1/pokemon/1/)
{
"abilities": [
{
"name": "overgrow",
"resource_uri": "/api/v1/ability/1/"
},
{
"name": "chlorophyll",
"resource_uri": "/api/v1/ability/2/"
}
],
"attack": 49,
"catch_rate": 45,
"created": "2013-11-02T12:08:25.745455",
"defense": 49,
"egg_cycles": 21,
"egg_groups": [
{
"name": "Monster",
"resource_uri": "/api/v1/egg/1/"
},
{
"name": "Grass",
"resource_uri": "/api/v1/egg/8/"
}
],
"ev_yield": "1 Sp Atk",
"evolutions": {
"level": 16,
"method": "level up",
"resource_uri": "/api/v1/pokemon/2/",
"to": "Ivysaur"
},
"exp": 64,
"growth_rate": "ms",
"happiness": 70,
"height": "2'4",
"hp": 45,
"male_female_ratio": "87.5/12.5",
"modified": "2013-11-02T13:28:04.914889",
"moves": [
{
"learn_type": "other",
"name": "Tackle",
"resource_uri": "/api/v1/move/1/"
},
{
"learn_type": "other",
"name": "Growl",
"resource_uri": "/api/v1/move/2/"
},
{
"learn_type": "level up",
"level": 10,
"name": "Vine whip",
"resource_uri": "/api/v1/move/3/"
}
],
"name": "Bulbasaur",
"national_id": 1,
"resource_uri": "/api/v1/pokemon/4/",
"sp_atk": 65,
"sp_def": 65,
"species": "seed pokemon",
"speed": 45,
"total": 318,
"types": [
{
"name": "grass",
"resource_uri": "/api/v1/type/5/"
},
{
"name": "poison",
"resource_uri": "/api/v1/type/8/"
}
],
"weight": "15.2lbs"
}
Evolutions class:
public class Evolutions
{
public int level { get; set; }
public string method { get; set; }
public string resource_uri { get; set; }
public string to { get; set; }
}
I tried http://json2csharp.com/ with http://pokeapi.co/api/v1/pokemon/19/ and what I see is
public class RootObject
{
//...
public List<Evolution> evolutions { get; set; }
//...
}
This pretty mush is your Pokemon class. So you need to declare Evolutions as list.