In my Dot Net Core Web project I have to dump the Json data to the the Database.
My json data is as follows
{
'FactTable': 'TranMast',
'LastCdt':'2018-03-01 01:19:17 pm',
'DigiAgentDetId':'12',
'DigiAgentId':'34',
'LastSeqNo':'23',
'Deleted':'1',
'DataSet':{
'TranDet':[
{'Id':'1','TranMastId':'53_25','AcMastId':'sdsd','Account':'sdsd','Amount':'23000','MemName':'dsds','LocId':'ewsds','PartyMastId':'dsdsd','PartyMemId':'23232','AcParentId':'dsdsd','Deleted':'1'},
{'Id':'2','TranMastId':'53_25','AcMastId':'sdsd','Account':'sdsd','Amount':'24000','MemName':'dsds','LocId':'ewsds','PartyMastId':'dsdsd','PartyMemId':'23232','AcParentId':'dsdsd','Deleted':'1'},
{'Id':'3','TranMastId':'53_25','AcMastId':'sdsd','Account':'sdsd','Amount':'25000','MemName':'dsds','LocId':'ewsds','PartyMastId':'dsdsd','PartyMemId':'23232','AcParentId':'dsdsd','Deleted':'1'}
]
}
}
I am construting above json to dataset as following
var myUtil = JsonConvert.DeserializeObject<MyTableUtilClass>(json);
Where MyTableUtilClass have the follwing structure
public class MyTableUtilClass
{
public string LastCdt { get; set; }
public string DigiAgentId { get; set; }
public string DigiAgentDetId { get; set; }
public string LastSeqNo { get; set; }
public string FactTable { get; set; }
public DataSet DataSet { get; set; }
}
While trying to dump the table in the dataset to the database. in follwing code i am getting the error
int result = adapter.Update(table);
The Error I Am getting is
Failed to convert parameter value from a String to a Boolean
I know the couse of the problem is the field name Deleted is of type bit.
Then in which format i have to include the bit data in the json string.
Related
I'm trying to deserialize some statistics in JSON format from valve's API. The code below doesn't throw any exceptions when deserializing, only when trying to use the statistics afterwards. None of the statistics have a value after deserialization. Valve's response looks like this:
"playerstats":{
"steamID":"",
"gameName":"",
"stats":[
{
"name":"deaths",
"value":5062
}, etc etc..
This is my Rust class (Rust being the game I'm getting statistics from.):
public class Rust
{
public int steamID { get; set; }
public string gameName { get; set; }
public Array stats { get; set; }
}
And this is the deserialization code:
Rust getStats = JsonConvert.DeserializeObject<Rust>(str);
foreach (var stat in getStats.stats) //< ----- Exception: Object reference not set to an instance of an object.
{
parsed += stat.ToString();
}
'parsed' is then returned and used to print out all statistics and 'str' is the json response from Valve. I pasted the entire JSON response on pastebin in-case the above data isn't enough: https://pastebin.com/uJZSTF3G
I've tried naming some of the statistics individually in the Rust class instead of using an Array.
I expect the output to show all of the deserialized statistics for example in a console.
As #Bagus Tesa suggested, try something like...
public class Rust
{
public int steamID { get; set; }
public string gameName { get; set; }
public List<RustStat> stats { get; set; }
}
public class RustStat
{
public string name { get; set; }
public string value { get; set; }
}
Edit
I changed the steamID property to string and added the full code below. This compiled for me successfully. Hope this helps!
public class Valve
{
public Rust playerstats { get; set; }
}
public class Rust
{
public string steamID { get; set; }
public string gameName { get; set; }
public List<RustStat> stats { get; set; }
}
public class RustStat
{
public string name { get; set; }
public string value { get; set; }
}
Valve valve = JsonConvert.DeserializeObject<Valve>(str);
foreach (RustStat stat in valve.playerstats.stats)
{
}
Hello i want to deserialize a class which contains a string, a bool and a List<[mystructtype>;When using JsonConvert.Deserialize<[myclass]> it deserializes the string and the bool correctly but not the List<[Struct]>.I have also changed the List<struct> with an array of structs.Both the class container and the struct are marked with Serializeable and i do not understand where the problem is.
Can anyone help me?
Struct
[Serializable]
public struct Status
{
//identifiers
public long playerId { get; set; }
public long groupId { get; set; }
public int type { get; set; }
}
Class Container
[Serializable]
class GatewayDeviceResponse
{
public bool status { get; set; } //gets deserialized good
public string message { get; set; } //gets deserialized good
public Status[] data { get; set; } // all members are defaults
}
Deserialization
IRestResponse response = client.Execute(request);
string result = Encoding.UTF8.GetString(response.RawBytes);
GatewayDeviceResponse resp = JsonConvert.DeserializeObject<GatewayDeviceResponse>(result);
return resp.data.ToList();
P.S The string is a response from a webserver,and i am using RestSharp for creating the server request and getting the response.The thing is the response string is good.The class is deserialized good excluding the collection.
What could the problem be?
P.S
The string response from the server i get is :
"{
\"status\":true,
\"message\":\"ok\",
\"data\":[
{
\"status\":{
\"playerId\":59,
\"groupId\":26,
\"type\":2,
\"deviceId\":\"abababa",
\"groupName\":\"srl\",
\"playerName\":\"Adrian\"
}
},
{
\"status\":{
\"playerId\":25,
\"groupId\":26,
\"type\":1,
\"deviceId\":\"lalal\",
\"groupName\":\"srl\",
\"playerName\":\"Alex\"
}
}
]
}"
The Status[] array elements are not supposed to be fully filled by the server response , just the 3 fields i have posted in the POCO/
I wrote a unit test as below and it passes and correctly deserialized with restsharp. Can you replace your response string and classes to check unit test still pass?
May be your class representation is not fit for your response. Take a little help from http://json2csharp.com/ and check your classes represents your json correctly.
[Test]
public void Can_Deserialize_Struct()
{
var data = "{ \"myList\":[{\"name\": \"test1234\"}] }";
JsonDeserializer json = new JsonDeserializer();
var output = json.Deserialize<MyTest>(new RestResponse { Content = data });
Assert.NotNull(output);
}
class MyTest
{
public List<MyStruct> MyList { get; set; }
}
struct MyStruct
{
public String name { get; set; }
}
According to your response string, your c# classes should represent your json as below :
public class Status
{
public int playerId { get; set; }
public int groupId { get; set; }
public int type { get; set; }
public string deviceId { get; set; }
public string groupName { get; set; }
public string playerName { get; set; }
}
public class StatusData
{
public Status status { get; set; }
}
public class GatewayDeviceResponse
{
public bool status { get; set; }
public string message { get; set; }
public List<StatusData> data { get; set; }
}
It does not related with type struct or class. You need to add another class in front of your status representation class. Because it starts as a json object in your response string.
I have the following class Visual Studio created from the JSON pasted below.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string id { get; set; }
public string comments { get; set; }
public DateTime createdDate { get; set; }
public DateTime modifiedDate { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
}
-----JSON-----
[{"id":"00a17000000LmTOAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:52:02.000+0000","modifiedDate":"2015-03-13T15:52:02.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmTTAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:53:19.000+0000","modifiedDate":"2015-03-13T15:53:19.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmTYAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:54:29.000+0000","modifiedDate":"2015-03-13T15:54:29.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmU7AAK","comments":"New Note Entered by Requester: This is a comment or note added from code","createdDate":"2015-03-13T16:39:43.000+0000","modifiedDate":"2015-03-13T16:39:43.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmW3AAK","comments":"added this comment from SalesF app as an agent","createdDate":"2015-03-13T17:37:24.000+0000","modifiedDate":"2015-03-13T17:37:24.000+0000","createdBy":"Agent","modifiedBy":"Agent"}]
I'm trying to create an object and do a foreach and get the data... I keep getting error Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly.
I have tried this among other things:
var jsonResponseNotes = JsonConvert.DeserializeObject<Rootobject>(GetCommentsByID());
Any Ideas would be greatly appreciated!!!
you just need the root class:
public class RootObject
{
public string id { get; set; }
public string comments { get; set; }
public string createdDate { get; set; }
public string modifiedDate { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
}
and then deserialize it like this:
var result = JsonConvert.DeserializeObject<List<RootObject>>(json);
This is a list of your object. You will need to deserialize as such. Your code should be:
var jsonResponseNotes = JsonConvert.DeserializeObject<List<Class1>>(GetCommentsByID());
Edit
Just noticed your root object property is an array. Still, I believe arrays deserialize into list objects. I've adjusted my code.
I have a strange issue that I can't wrap my head around. I am trying to create an "export to csv" function for my MVC4 application where the relevant JSON is passed via an ajax call to my ActionResult. The ActionResult deserializes the stringify'd JSON (with JSON.Net), writes it to a file in csv format, then returns the server path to the new file. My success callback then receives the path and calls the url to download.
This works fine locally, but on my live test server I get the following exception:
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.
The JSON (and subsequently the objects they are deserialized to) are slightly complex. They come from a grouped subset of a SlickGrid DataView. I was getting circular reference exceptions when I included the aggregate information for column totals (this is only relevant to those that are versed in SlickGrid, I do not believe the data being passed to the server is an issue), but I've removed them before passing the JSON to the server. Here is my JSON to C# class structure:
[Serializable]
public class Row
{
public int id { get; set; }
public DateTime DateCreated { get; set; }
public int RefNo { get; set; }
public string ClientName { get; set; }
public string Plate { get; set; }
public string Address1 { get; set; }
public int? ProductID { get; set; }
public string Product { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
}
[Serializable]
public class RootReportObject
{
public bool __group { get; set; }
public int level { get; set; }
public int count { get; set; }
public string value { get; set; }
public string title { get; set; }
public int collapsed { get; set; }
public List<Row> rows { get; set; }
public object groups { get; set; }
public string groupingKey { get; set; }
}
The only thing that I'm thinking is that, because of the way the data is structured, the List<> of rows in the root object may be throwing the circular references during deserializtion because a group does not necessarily have unique row references.
My question is why does it work fine locally?? I have no idea what I'm missing.
That's great that the [ScriptIgnore] attribute is helping. Also, something to be completely sure of is that all of your URL paths, including in your AJAX code, resolve correctly to the application root. When some of these are wrong, this is a notorious source of problems during the move from development to production.
It doesn't sound like it is necessarily the primary issue but I don't have any understanding of your app's design. It's definitely worth looking over.
i want to convert Dictionary into Json. the key is a string and the value is a ICollection of CompaignModel :
IDictionary<string, ICollection<BuzzCompaignModel>> BuzzCompaignByInterest ;
and here is what contain BuzzCompaign Model :
public class BuzzCompaignModel
{
public long BuzzCompaignId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime EndDate { get; set; }
}
how can i convert BuzzCompaignByInterest into JSON
Use Json.NET and JsonConvert
http://james.newtonking.com/projects/json/help/SerializingJSON.html
It doesn't matter dictionary or object are serialising to Json