Deserialize Json Object containing multiple sub Array and Bulk Copy in SQL - c#

I have the following JSON data containing multiple sub array, Any suggestion how can Deserialize this and print on my page.
NEXT STEP
: After this, I need to insert this data in SQL using bulk copy features.
C# Code
collect mydata= new JavaScriptSerializer().Deserialize<collect >(json);
foreach (var item in mydata.results)
{
context.Response.Write(item.newPrice + item.pName);
}
public class collect
{
public List<collection1> results { get; set; }
}
public class collection1
{
public List<data> collection1 { get; set; }
}
public class data
{
public string newPrice { get; set; }
public string pName { get; set; }
}
JSON Array :
{
"name": "Test 1",
"count": 3,
"version": 2,
"lastsuccess": "Thu Oct 09 2014 05:42:17 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"newPrice": "12787",
"pName": "Sony Xperia M Dual Black"
},
{
"newPrice": "24999",
"pName": "LG Google Nexus 5 16 GB (Black)"
}
]
}
}

To answer your question regarding how to de serialize the JSON here is a solution... I am not sure what you mean by "Print on my page" as your question does not put that into any context however...
I used http://json2csharp.com to create the poco classes below...
public class Collection1
{
public string newPrice { get; set; }
public string pName { get; set; }
}
public class Results
{
public List<Collection1> collection1 { get; set; }
}
public class RootObject
{
public string name { get; set; }
public int count { get; set; }
public int version { get; set; }
public string lastsuccess { get; set; }
public Results results { get; set; }
}
Then the following code will deserialize the JSON to C#...
RootObject myData = new JavaScriptSerializer().Deserialize<RootObject>(json);
You can now do with it as you please, in terms of your bulk insert... thats another question really so please start a new one.

Related

Deserialize Json into C#

I got some Json, that looks like this:
[
{
"starttime": "2020-02-27T14:30:00Z",
"endtime": "2020-02-27T14:40:00Z"
},
{
"Temp": {
"value": 3
},
"Pressure": {
"value": 29
},
"Humidity": {
"value": 85
}
}
]
I would like to deserialize it onto a object on the form:
public class Sample {
public string Name {get; set;}
public int Value {get;set;}
}
and then get 3 instances where name is set to either Temp, Pressure, Humidity, and Value set to 3, 29, 85
I don't really care about the start-/endtime part.
Any help would be greatly appreciated...
/Søren
Update:
Came up with this myself:
var tmp = JsonConvert.DeserializeObject<JArray>(content);
var samples = tmp.
SelectMany(x => ((JToken) x).Children())
.Where(x => !((JProperty) x).Name.Contains("time"))
.Select(x =>
{
var tmp2 = x.First.ToObject<Sample>();
tmp2.name = ((JProperty) x).Name;
return tmp2;
})
.ToList();
but I think Pavel's solution below, is more readable....
You can use Json.Linq to get a list of Sample objects from your json. Parse json to JArray instance, then enumerate all properties of the last object to get the names and values
var array = JArray.Parse(json);
var samples = ReadSamples(array.Last());
foreach (var sample in samples)
{
Console.WriteLine($"{sample.Name} {sample.Value}");
}
IEnumerable<Sample> ReadSamples(JToken data)
{
foreach (JProperty item in data)
{
yield return new Sample()
{
Name = item.Name,
Value = item.Value["value"]?.Value<int>() ?? 0
};
}
}
The output will be the following
Temp 3
Pressure 29
Humidity 85
It's also possible to do the same using System.Text.Json API, which is available from .NET Core 3.x
Per your posted JSON, you would get a model like below. Use http://json2csharp.com/#
public class Temp
{
public int value { get; set; }
}
public class Pressure
{
public int value { get; set; }
}
public class Humidity
{
public int value { get; set; }
}
public class RootObject
{
public DateTime starttime { get; set; }
public DateTime endtime { get; set; }
public Temp Temp { get; set; }
public Pressure Pressure { get; set; }
public Humidity Humidity { get; set; }
}
If your JSON is not dynamic, creating classes which model your JSON is a good idea.
An easy way is to Copy JSON to clipboard -> Open Visual Studio -> Edit -> Paste Special -> Paste JSON as classes.
This should give you the following classes:
public class Class1
{
public DateTime starttime { get; set; }
public DateTime endtime { get; set; }
public Temp Temp { get; set; }
public Pressure Pressure { get; set; }
public Humidity Humidity { get; set; }
}
public class Temp
{
public int value { get; set; }
}
public class Pressure
{
public int value { get; set; }
}
public class Humidity
{
public int value { get; set; }
}
And now you can deserialize the JSON array to List<Class1>using the Newtonsoft.Json NuGet package:
using Newtonsoft.Json;
using System.Collections.Generic;
...
string json = #"[
{
""starttime"": ""2020 - 02 - 27T14: 30:00Z"",
""endtime"": ""2020-02-27T14:40:00Z""
},
{
""Temp"": {
""value"": 3
},
""Pressure"": {
""value"": 29
},
""Humidity"": {
""value"": 85
}
}
]";
var myObject = JsonConvert.DeserializeObject<List<Class1>>(json);

read multiple Json data from webservice

i have a web service that returns a Json string.
my problem is that i have difficulties to read it
i tried with:
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
var myobj = jsSerializer.Deserialize<List<CinfoRichiesta>>(jsonData);
but how can i get values from "students" and "locations"?
with javascript i used :" var j = jQuery.parseJSON(msg.d);" but i think with c# code would be different
this is an example of string:
{"Questions":{
"id":"2",
"BOOK":"3",
"students":{
"class":"3",
"theme","43"
},
"locations":{
"h":"0",
"L":"3"
}
}
}
First off, your JSON isn't valid so thats the first problem you have. You can verify this at http://jsonlint.com/ for example.
i have currently fixed this in the following way:
{
"Questions": {
"id": "2",
"BOOK": "3",
"students": {
"class": "3",
"theme": "na",
"43": "na"
},
"locations": {
"h": "0",
"L": "3"
}
}
}
Second your class should be correct, with the current JSON this should look something like this
public class Rootobject
{
public Questions Questions { get; set; }
}
public class Questions
{
public string id { get; set; }
public string BOOK { get; set; }
public Students students { get; set; }
public Locations locations { get; set; }
}
public class Students
{
public string _class { get; set; }
public string theme { get; set; }
public string _43 { get; set; }
}
public class Locations
{
public string h { get; set; }
public string L { get; set; }
}
After this you can deserialize it like this
var myobj = jsSerializer.Deserialize<List<Rootobject>>(jsonData);
And then you can get the information like this
myobj.Questions.students._class
You're deserializing to a collection of type CinfoRichiesta, which should hold a property value for students and locations.
Assuming that your JSON is correctly formatted and your class definition is suitable for the response (I recommend double checking it by pasting the entire response string into json2csharp.com)
Once that's all validated, you should be able to see the students and locations collections internally like so:
foreach(Question q in myobj)
{
Console.WriteLine(q.students.class)
}
which should give you the result of 3.
edit
I think your main question is why you're unable to access the properties of students and locations. Make sure Students is its own class as such:
public class Students
{
public int class { get; set; }
public int theme { get; set; }
}
and your locations class should be:
public class Locations
{
public int h { get; set; }
public int l { get; set; }
}
You should then have a questions class that instaniates both students and locations, as such:
public class Questions
{
public int id { get; set; }
public int book { get; set; }
public Student students { get; set; }
public Locations locations { get; set; }
}
When working with JSON deserialization, it's important that your object property names (ie class) match the response string in terms of case. So If you wrote it as public int Theme, it won't directly map.
Slightly annoying in terms of coding standards, but hey ho :-)

Parsing JSON using Newtonsoft.JSON

I have a JSON string as follows:
[{
"ID":"1",
"title":"New Product Launch",
"fro":"Vitamin D",
"summary":"New Vitamin D prodcut",
"type":"image",
"link":"http:\/\/www.foo.in\/upload\/image\/1.png",
"detail":"13-11-2013",
"fileSize":23763
},
{
"ID":"2",
"title":"New Product Launch",
"fro":"Vitamin D",
"summary":"New Vitamin D prodcut",
"type":"image",
"link":"http:\/\/www.foo.in\/upload\/image\/1.png",
"detail":"13-11-2013",
"fileSize":23763
}]
My code for parsing is as follows:
AnnouncementListObject resultsJSON = JsonConvert.DeserializeObject<AnnouncementListObject>(json); //line1
using (AnnouncementDataContext context = new AnnouncementDataContext(Con_String))
{
AnnouncementData alData = new AnnouncementData();
alData.announcementID = int.Parse(resultsJSON.ID);
.
.
.
.
context.AnnouncementData.InsertOnSubmit(alData);
context.SubmitChanges();
}
EDIT:
public class AnnouncementListObject
{
public string ID { get; set; }
public string title { get; set; }
public string fro { get; set; }
public string summary { get; set; }
public string type { get; set; }
public string link { get; set; }
public string detail { get; set; }
public object fileSize { get; set; }
}
But it throws error on line 1 where I deserialize the JSON data. I want to store this multiple data rows in database. I cannot use foreach loop here as JSON data is not enclosed under root node. Any help on how should I go about?
Try deserializing to a list like so
var resultsJSON = JsonConvert.DeserializeObject<List<AnnouncementListObject>>(json); //line1
You're dealing with an array of JSON objects, but you're trying to cast it as a single object.

RestSharp JSON Array deserialization

I launch this RestSharp query in JSON format:
var response = restClient.Execute<Report>(request);
The response I get contains this data
[
{
"Columns":
[
{"Name":"CameraGuid","Type":"Guid"},
{"Name":"ArchiveSourceGuid","Type":"Guid"},
{"Name":"StartTime","Type":"DateTime"},
{"Name":"EndTime","Type":"DateTime"},
{"Name":"TimeZone","Type":"String"},
{"Name":"Capabilities","Type":"UInt32"}
],
"Rows":
[
[
"00000001-0000-babe-0000-00408c71be50",
"3782fe37-6748-4d36-b258-49ed6a79cd6d",
"2013-11-27T17:52:00Z",
"2013-11-27T18:20:55.063Z",
"Eastern Standard Time",
2147483647
]
]
}
]
I'm trying to deserialize it into this group of classes:
public class Report
{
public List<ReportResult> Results { get; set; }
}
public class ReportResult
{
public List<ColumnField> Columns { get; set; }
public List<RowResult> Rows { get; set; }
}
public class ColumnField
{
public string Name { get; set; }
public string Type { get; set; }
}
public class RowResult
{
public List<string> Elements { get; set; }
}
Unfortunately, the result data is null and I get this exception:
Unable to cast object of type 'RestSharp.JsonArray' to type
'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
I cannot figure out what is wrong here.
I little help would be greatly appreciated.
Try this:
var response = restClient.Execute<List<ReportResult>>(request);
EDIT
You should also change ReportResult to:
public class ReportResult
{
public List<ColumnField> Columns { get; set; }
public List<List<string>> Rows { get; set; }
}
and you can get rid of Report and RowResult.
There is another way by creating wrapper class:
public class ThirdPartySuggesters : List<ThirdPartySuggester> {}
var response = client.Execute<ThirdPartySuggesters>(request);

How to create class for JSON web service result in windows phone 7?

how can I create class for JSON web service result? This is my JSON result which i get from google api. so, how to create class and deserialization for this JSON object.
I created class to deserialization this JSON object like this,
string mapdetail = e.Result;
var djosn = new DataContractJsonSerializer(typeof(mapResult));
var mstr = new MemoryStream(Encoding.UTF8.GetBytes(mapdetail));
mapResult reslt = (mapResult)djosn.ReadObject(mstr);
mapResult class:
[DataContract]
public class mapResult
{
[DataMember]
public string status
{
get;
set;
}
[DataMember]
public IList<Resultdetail> result
{
get;
set;
}
}
So i creadet list for result details and others:
[DataContract]
public class Resultdetail
{
[DataMember]
public List<string> types
{
get;
set;
}
[DataMember]
public string formatted_address
{
get;
set;
}
[DataMember]
public List<object> address_components
{
get;
set;
}
[DataMember]
public List<Geometry> geometry
{
get;
set;
}
}
[DataContract]
public class Geometry
{
[DataMember]
public List<GeoLocation> location
{
get;
set;
}
[DataMember]
public string location_type
{
get;
set;
}
[DataMember]
public List<object> viewport
{
get;
set;
}
[DataMember]
public List<object> bounds
{
get;
set;
}
}
[DataContract]
public class GeoLocation
{
[DataMember]
public double lat
{
get;
set;
}
[DataMember]
public double lng
{
get;
set;
}
}
Now I'm getting Null reference;
There were a few issues with your DatContract classes.
I've corrected these below, commented out the original lines and added a comment about what was specifically wrong.
[DataContract]
public class mapResult
{
[DataMember]
public string status { get; set; }
[DataMember]
//public IList<Resultdetail> result { get; set; }
// Misspelt property name and use of interface rather than concrete type
public List<Resultdetail> results { get; set; }
}
[DataContract]
public class Resultdetail
{
[DataMember]
public List<string> types { get; set; }
[DataMember]
public string formatted_address { get; set; }
[DataMember]
public List<object> address_components { get; set; }
[DataMember]
//public List<Geometry> geometry { get; set; }
// Json does not contain an array/list of these
public Geometry geometry { get; set; }
}
[DataContract]
public class Geometry
{
[DataMember]
//public List<GeoLocation> location { get; set; }
// Json does not contain an array/list of these
public GeoLocation location { get; set; }
[DataMember]
public string location_type { get; set; }
[DataMember]
// public List<object> viewport { get; set; }
// Json does not contain an array/list of these
public object viewport { get; set; }
[DataMember]
//public List<object> bounds { get; set; }
// Json does not contain an array/list of these
public object bounds { get; set; }
}
The following code shows that this works:
var jsonStr = "{\"status\": \"OK\", \"results\": [ { \"types\": [ \"route\" ], \"formatted_address\": \"7th Main Rd, Koramangala, sengaluru, Karnataka 560034, India\", \"address_components\": [ { \"long_name\": \"7th Main Rd\", \"short_name\": \"7th Main Rd\", \"types\": [ \"route\" ] }, { \"long_name\": \"Koramangala\", \"short_name\": \"Koramangala\", \"types\": [ \"sublocality\", \"political\" ] }, { \"long_name\": \"Bengaluru\", \"short_name\": \"Bengaluru\", \"types\": [ \"locality\", \"political\" ] }, { \"long_name\": \"sengaluru\", \"short_name\": \"sengaluru\", \"types\": [ \"administrative_area_level_2\", \"political\" ] }, { \"long_name\": \"Karnataka\", \"short_name\": \"Karnataka\", \"types\": [ \"administrative_area_level_1\", \"political\" ] }, { \"long_name\": \"India\", \"short_name\": \"IN\", \"types\": [ \"country\", \"political\" ] }, { \"long_name\": \"560034\", \"short_name\": \"560034\", \"types\": [ \"postal_code\" ] }],\"geometry\": { \"location\":{ \"lat\": 12.9259085, \"lng\": 77.6334715 }, \"location_type\": \"GEOMETRIC_CENTER\", \"viewport\": { \"southwest\": { \"lat\": 12.9227118, \"lng\": 77.6301852 }, \"northeast\": { \"lat\": 12.929007, \"lng\": 77.6364805}}, \"bounds\": { \"southwest\": { \"lat\": 12.9247615, \"lng\": 77.6330486 },\"northeast\": { \"lat\": 12.9269574, \"lng\": 77.6336171 }}}}]}";
// If using json.net (http://json.codeplex.com/)
var des = JsonConvert.DeserializeObject<mapResult>(jsonStr);
// If using System.Runtime.Serialization.Json
var djosn = new DataContractJsonSerializer(typeof(mapResult));
var mstr = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
des = (mapResult)djosn.ReadObject(mstr);
var latitude = des.results[0].geometry.location.lat;
var longitude = des.results[0].geometry.location.lng;
Note that my code is tested with your sample json object only and is not guaranteed to work with everything returned by the web service. You're also deserialising quite a lot to object which may be awkward to work with if you want more than just the latitude and longitude.
I note that your top-level list is called result whereas the JSON name is results btw - could it be as simple as that? Maybe the deserializer is ignoring the results value because you don't have a property of that name.
If that doesn't work... You've got 7 dereferencing operations in that statement. (4 obvious ones and 3 array indexing operations). That's an awful lot of possible failure points. I suggest you put a break point on that statement (to break before it executes) and then use the watch window to look at what results you've actually got.
(Personally I've used Json.NET in Windows Phone 7 rather than the built-in libraries, but I'm sure the latter should work too.)

Categories