I have the following JSON string:
[
{
"name":"Test diagnosis",
"code":"324324",
"table":"EXAMPLE",
"addedby":"EDnurse",
"dateadded":3243243,
"qualifier":[
{
"name":"Qualifier",
"value":"Confirmed Diagnosis",
"code":"23434434",
"prefix":"[C] "
},
{
"name":"Left/Right",
"value":"Bilateral",
"code":"324343",
"suffix":" - Bilateral"
}
],
"prefix":"[C] ",
"suffix":" - Bilateral"
}
]
You can see that the Qualifier field in this JSON String is nested and has 2 objects.
I am working on a package that parses this JSON string using C# in SSIS. I can Parse the string with one object of qualifier, but when I add the second object (left/right), and attempt to turn the string into an array, I receive an error.
Without array (works with one Qualifier object):
Diagnosis diagnosis = js.Deserialize<Diagnosis>(reviewConverted);
With array (returns error stating that I cannot implicitly convert type diagnosis to type diagnosis ):
Diagnosis diagnosis = js.Deserialize<List<Diagnosis>>(reviewConverted);
I also use the following Class to define my diagnosis fields:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SC_8aae662509ae4bab8491323924579173
{
class Diagnosis
{
public string name { get; set; }
public string code { get; set; }
public string table { get; set; }
public string addedby { get; set; }
public string dateadded { get; set; }
public qualifier Qualifier { get; set; }
public string prefix { get; set; }
public string suffix { get; set; }
}
}
Here is my qualifier class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SC_8aae662509ae4bab8491323924579173
{
class qualifier
{
public string name { get; set; }
public string value { get; set; }
public string code { get; set; }
public string prefix { get; set; }
}
}
As far as i can tell, based on what you're saying, 1 Diagnosis object, can contain multiple Qualifier objects. So what you need to do is the following:
First, change your Diagnosis class to have the following property:
public qualifier List<Qualifier> { get; set; }
instead of
public qualifier Qualifier { get; set; }
Also the following statement is what gives you an error:
Diagnosis diagnosis = js.Deserialize<List<Diagnosis>>(reviewConverted);
You are trying to store in a Diagnosis objext a List of Diagnosis object, which makes no sense of course.
Did you try like below?
class Diagnosis
{
public string name { get; set; }
public string code { get; set; }
public string table { get; set; }
public string addedby { get; set; }
public string dateadded { get; set; }
public List<Qualifier> qualifier { get; set; }
public string prefix { get; set; }
public string suffix { get; set; }
}
Related
I'm following the tutorial given here for deserializing an embedded xml document.
My Xml doc:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfAgency xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DbAgencyDefinition>
<Name>RTD</Name>
<Country>USA</Country>
<City>Denver</City>
<State>CO</State>
<GtfsZipUrlDirectory>http://www.address.com/etc/</GtfsZipUrlDirectory>
<GtfsZipUrlFileName>file_name.zip</GtfsZipUrlFileName>
</DbAgencyDefinition>
</ArrayOfAgency>
My class I'm deserializing to:
public class DbAgencyDefinition
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string GtfsZipUrlDirectory { get; set; }
public string GtfsZipUrlFileName { get; set; }
public string State { get; set; }
}
The code that's trying to deserialize the XML to a list of DbAgencyDefinition:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(DbAgencyDefinition)).Assembly;
Stream stream = assembly.GetManifestResourceStream("MyNamespace.Resources.xml.AgencyDefinitions.xml");
var agencies = new List<DbAgencyDefinition>();
using (var reader = new StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(List<DbAgencyDefinition>));
agencies = (List<DbAgencyDefinition>)serializer.Deserialize(reader);
}
The error I'm getting is:
System.Exception: There is an error in XML document. <ArrayOfAgency xmlns=''> was not expected
I've tried a million things with the XML, marking the class as Serializable, and it always returns this error. I looked at the code samples that the tutorial gives and I can't figure out why I'm getting this error.
VS for Windows, and maybe on Mac as well, has a special tool that will convert copied Xml into autogenerated classes. Now, it's not perfect but if you take your Xml file it generates a couple of classes similar to this:
public class ArrayOfAgency
{
public ArrayOfAgencyDbAgencyDefinition DbAgencyDefinition { get; set; }
}
public class ArrayOfAgencyDbAgencyDefinition
{
public string Name { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string State { get; set; }
public string GtfsZipUrlDirectory { get; set; }
public string GtfsZipUrlFileName { get; set; }
}
As you might notice ArrayOfAgency is determined as a class holding a DbAgencyDefinition, which is why it's throwing an error while trying to deserialize it directly into a List<DbAgencyDefinition>. The type and what the serializer is expecting are not quite the same.
var serializer = new XmlSerializer(typeof(ArrayOfAgency));
var agencies = ((ArrayOfAgency)serializer.Deserialize(reader)).DbAgencyDefinition;
Also, as I mentioned the auto-generation may not be perfect because ArrayOfAgency may need to hold an array instead of a direct class if there can be more than one DbAgencyDefinition possible in Xml.
public class ArrayOfAgency
{
public ArrayOfAgencyDbAgencyDefinition[] DbAgencyDefinition { get; set; }
}
If you need more help or info on Xml Serialization check out the docs.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication120
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
using (var reader = new StreamReader(FILENAME, Encoding.UTF8))
{
var serializer = new XmlSerializer(typeof(ArrayOfAgency));
ArrayOfAgency agencies = (ArrayOfAgency)serializer.Deserialize(reader);
}
}
}
public class ArrayOfAgency
{
public DbAgencyDefinition DbAgencyDefinition { get; set; }
}
public class DbAgencyDefinition
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string GtfsZipUrlDirectory { get; set; }
public string GtfsZipUrlFileName { get; set; }
public string State { get; set; }
}
}
I want to read some data from a JSON API in SSIS and write it to a table in SQL Server. I've solved the task using a 3rd party, but the solution isn't that elegant, so now I'm trying to script it myself in Visual Studio using SSIS's script component.
I've researched around the web for solutions, and ended with this result. So far, I'm fairly confident about what is going on, but I lack the final direction for this. I know I need to somehow map the output to the columns I've created in SSIS.
I guess I have to do something around CreateNewOutputRows(), but I'm not sure what. Can someone please help me out on this? Also, since this is more or less my first ever c# script, I would also appreciate it, if there's a way easier solution OR if it is in some way inappropriate etc.
First of all, the output from the API looks like this (API documentation here):
"data":[
{
"created_at":"2016-03-12 09:45:00",
"created_at_unix":1457772300,
"shop_name":"DK - Some name",
"location_id":1111,
"custom_location_id":"2222",
"custom_shop_id":"2222",
"shop_id":3333,
"count_in":"1",
"count_out":"1",
"timekey":3
}
The script I've got so far is
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Linq;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public static void Main()
{
//Test api
var url = "https://login.vemcount.com/api/fetch_data/?data={"api_key":"xxxxxxx","type":"company_id","id":"10","date_from":"2019-01-01 00:00","interval":"15min", "group_by":"shop_id"}";
var json = new WebClient().DownloadString(url);
var root = JsonConvert.DeserializeObject<RootObject>(json);
//Printing last record
Console.WriteLine(root.data.Last().created_at);
}
public class data
{
public string created_at { get; set; }
public int created_at_unix { get; set; }
public string shop_name { get; set; }
public int location_id { get; set; }
public string custom_location_id { get; set; }
public string custom_shop_id { get; set; }
public int shop_id { get; set; }
public string count_in { get; set; }
public string count_out { get; set; }
public int timekey { get; set; }
}
public class RootObject
{
public List<data> data { get; set; }
}
public override void CreateNewOutputRows()
{
}
}
You'll put all that code in CreateNewOutputRows().
First you have to manually add all the columns to the script component. In the example here I only added 2 columns:
The code goes in CreateNewOutPutRows(). I don't have Newtonsoft, just using the JavaScriptSerializer here to show a working example so you can see how to hook it up:
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Web.Script.Serialization;
using System.Collections.Generic;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void CreateNewOutputRows()
{
string json = #"{""data"":[{""created_at"":""2016-03-12 09:45:00"",""created_at_unix"":1457772300,""shop_name"":""DK - Some name"",""location_id"":1111,""custom_location_id"":""2222"",""custom_shop_id"":""2222"",""shop_id"":3333,""count_in"":""1"",""count_out"":""1"",""timekey"":3},{""created_at"":""2016-03-12 09:45:00"",""created_at_unix"":1457772300,""shop_name"":""test2"",""location_id"":1111,""custom_location_id"":""2222"",""custom_shop_id"":""2222"",""shop_id"":3333,""count_in"":""1"",""count_out"":""1"",""timekey"":3}]}";
RootObject Test = new JavaScriptSerializer().Deserialize<RootObject>(json);
/*
* This is where data gets added to the output buffer.
* After AddRow() you are basically mapping the column you manually added(on the left) to the data(on the right).
* using a foreach loop to loop through the deserialize json
*/
foreach (var item in Test.data)
{
Output0Buffer.AddRow();
Output0Buffer.createdat = item.created_at;
Output0Buffer.shopname = item.shop_name;
}
}
public class RootObject
{
public List<data> data { get; set; }
}
public class data
{
public string created_at { get; set; }
public int created_at_unix { get; set; }
public string shop_name { get; set; }
public int location_id { get; set; }
public string custom_location_id { get; set; }
public string custom_shop_id { get; set; }
public int shop_id { get; set; }
public string count_in { get; set; }
public string count_out { get; set; }
public int timekey { get; set; }
}
}
Then in this example, just using a record set destination and enabled data viewer so you can see the individuals rows come back out:
I have a json object and I am trying to convert it to my c# object. Here is my JSON:
{"GuvenlikNoktaArray": {"GuvenlikNoktası": [{"Id": 1,"GuvenlikNoktası1":"SANTIYE","KartNo":"000001889174217","Sira": 1},{"Id": 2,"GuvenlikNoktası1":"INSAAT","KartNo":"000000803567858","Sira": 2},{"Id": 3,"GuvenlikNoktası1":"ÇALISMA","KartNo":"000003417926233","Sira": 3},{"Id": 4,"GuvenlikNoktası1":"GÜVENLIK","KartNo":"000001888909897","Sira": 4}]}}
And my c# class:
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
And last, my convert try:
public void AddIstasyon(string json_string)
{
GuvenlikNoktası result = new JavaScriptSerializer().Deserialize<GuvenlikNoktası>(json_string);
}
I don't get any errors but when I debuged, I see that all attributes inside 'result' are null. It seems like an empty object. How can I get a correct 'GuvenlikNoktası' object ? (Btw I am pretty sure I am getting the json object correctly).
If you must keep this JSON structure as-is you may use JObject to navigate inside your JSON properties until you reach your target objects to deserizlize. Please can you try the code below;
PS: This code uses Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SO_39847703
{
class Program
{
static void Main(string[] args)
{
string json = "{\"GuvenlikNoktaArray\": {\"GuvenlikNoktası\": [{\"Id\": 1,\"GuvenlikNoktası1\":\"SANTIYE\",\"KartNo\":\"000001889174217\",\"Sira\": 1},{\"Id\": 2,\"GuvenlikNoktası1\":\"INSAAT\",\"KartNo\":\"000000803567858\",\"Sira\": 2},{\"Id\": 3,\"GuvenlikNoktası1\":\"ÇALISMA\",\"KartNo\":\"000003417926233\",\"Sira\": 3},{\"Id\": 4,\"GuvenlikNoktası1\":\"GÜVENLIK\",\"KartNo\":\"000001888909897\",\"Sira\": 4}]}}";
AddIstasyon(json);
}
public static void AddIstasyon(string json_string)
{
dynamic jsonObject = JObject.Parse(json_string);
string jsonToDeserializeStrongType = jsonObject["GuvenlikNoktaArray"]["GuvenlikNoktası"].ToString();
List<GuvenlikNoktası> result = JsonConvert.DeserializeObject<List<GuvenlikNoktası>>(jsonToDeserializeStrongType); ;
}
}
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
public class GüvenlikNoktasıOlay
{
}
public class PanikButonuAlarmlari
{
}
}
Hope this helps
Your JSON data and your class definition do not fit together. Therefore the default values (NULL) are provided by the serializer.
In order to deserialize the given JSON data you need a class structure like:
public class Root
{
public LevelOne GuvenlikNoktaArray {get; set;}
}
public class LevelOne {
public IEnumerable<GuvenlikNoktası> GuvenlikNoktası {get; set;}
}
You can use this class.
public class GuvenlikNoktası
{
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public int Sira { get; set; }
}
public class GuvenlikNoktaArray
{
public IList<GuvenlikNoktası> GuvenlikNoktası { get; set; }
}
public class Example
{
public GuvenlikNoktaArray GuvenlikNoktaArray { get; set; }
}
You can use this link For your referencehttp://jsonutils.com/.
I have the following Json: http://pastebin.com/pd62g62w
How can I deserialize "sensors" and turn it into an array/list ?
I'm using Json.NET for the deserialization.
DeviceModel deviceModel = new DeviceModel();
deviceModel = JsonConvert.DeserializeObject<DeviceModel>(json);
My current code:
using System;
using Newtonsoft.Json;
namespace Homecheck.Models {
public class DeviceModel {
public string error { get; set; }
public string errorType { get; set; }
[JsonProperty(PropertyName = "_id")]
public string id { get; set; }
[JsonProperty(PropertyName = "_user")]
public string user { get; set; }
[JsonProperty(PropertyName = "_serial")]
public string serial { get; set; }
}
}
Create a class for sensors objects
public class Sensor {
public bool Active { get; set; }
[JsonProperty(PropertyName = "_description")]
public bool Description { get; set; }
/* and so on */
}
And then add it to your model as IEnumerable<Sensor> property:
public class DeviceModel {
/* existing properties omitted */
public IEnumerable<Sensor> Sensors { get; set; }
}
IEnumerable<Sensor> gives you an interface to go through all elements.
You can also use IList<Sensor> if you want list semantics (add, remove, access by index), or use array Sensor[] if you just want to have access by index.
My project is a Web project for MVC4 and I am trying to add a controller after adding a connection string to the web.config folder, but every time i try to add it, i get the following message:
Unable to retrieve metadata for TestFFL14.Models.LivePlayers. Object Reference not set to an instance of an object
Here is the LivePlayers Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace TestFFL14.Models
{
public class LivePlayers
{
public int ID { get; set; }
public int Nid { get; set; }
public string Plyr { get; set; }
public string Team { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
}
public class LivePlayersDBContext : DbContext
{
public DbSet<LivePlayers> Players { get; set; }
}
}
I am trying to use this connection string but not having any success:
<add name="LivePlayersDBContext" connectionString="Server=127.0.0.1;Port=5432;Database=testdb;User Id=pkioko;Password=stunner1" providerName="Npgsql" />
What am i doing wrong?
Try this.
Add below LivePlayersDBContext constructor with connectionstring name as parameter to base constructor
public class LivePlayersDBContext : DbContext
{
public LivePlayersDBContext ():base("LivePlayersDBContext")
{
}
public DbSet<LivePlayers> Players { get; set; }
}