[SOLVED] applied given solution, works fine!
Aim of the program: Save/reload previous data when user opens and closes the program.
I used to (de)serialize successfully with one object(obj), now I have two different objects of different classes.
I tried to combine them by looking at other posts; I put them in object array and give that object array when (de)serializing as parameter.
I do initialize for example like this; obj.flag1 = true; before
calling serialize() in other methods.(I didn't put them for simplicity since I already stated the functionality of methods)
It says objects are null, but logically if obj2 and obj were null, it should have given the error for obj standalone. It won't read empty file I handled it. The moment I tried to combine two object it started to give me null error for both of them. I am about to rip my hair, can someone please help?
[Serializable]
public partial class UI : Form
{
FlagClass obj;
CurrentAmplitude obj2;
object[] seri_obj;//combine multiple objects
//deserialization is performed in constructor
public UI()
{
InitializeComponent();
seri_obj = new object[] { obj, obj2 };
input += ".txt";
//default path + new filename
path_combined = Path.Combine(root, input);
//it won't try to read empty file
if (!File.Exists(path_combined))
{
using (var stream = File.Create(path_combined))
{
}
}
else //already have that file,so when user opens the program, data is loaded from file
{
//read booleans and inetegres
string json2 = File.ReadAllText(path_combined);
string FormattedJson = FormatJson(json2);
seri_obj = JsonConvert.DeserializeObject<object[]>(FormattedJson);
}
}
private static string FormatJson(string json)
{
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
//I do serialization here
void Serialize()
{
string json = JsonConvert.SerializeObject(seri_obj, Formatting.Indented);
File.WriteAllText(path_combined, json);
}
String values are in this class via "obj2"
[Serializable]
class CurrentAmplitude
{
//this class has the string values
[JsonProperty(PropertyName = "value1")]
public int value1 { get; set; }
[JsonProperty(PropertyName = "value2")]
public string value2 { get; set; }
[JsonProperty(PropertyName = "value3")]
public string value3 { get; set; }
[JsonProperty(PropertyName = "value4")]
public string value4 { get; set; }
[JsonProperty(PropertyName = "value5")]
public string value5 { get; set; }
public CurrentAmplitude(){
}
}
Boolean values are in this class via "obj"
[Serializable]
class FlagClass
{
//this class has the boolean values
[JsonProperty(PropertyName = "flag1")]
public bool flag1 { get; set; }
[JsonProperty(PropertyName = "flag2")]
public bool flag2 { get; set; }
public FlagClass()
{
}
}
Where you are deserializing:-
seri_obj = JsonConvert.DeserializeObject<object[]>(FormattedJson);
You are asking the deserializer to return an array raw objects, which will result in an array of JObject types, not your FlagClass and CurrentAmplitude types.
You're also setting seri_obj, but never assigning the values in seri_obj to your obj or obj2 variables, which is why the compiler is warning you.
You would be better off having an umbrella configuration class like this:-
class Configuration
{
public Flag { get; set; } = new FlagClass();
public CurrentAmplitude { get; set; } = new CurrentAmplitude();
}
Then just deserialize/serialize an instance of your Configuration class when you want to load/save...
// create config object if new
var config = new Configuration();
// to save
var json = JsonConvert.SerializeObject(config);
// to load
var config = JsonConvert.DeserializeObject<Configuration>(json);
// get/set config values
config.Flag.flag2 = false;
Here is a more complete example:-
void Main()
{
// create a new blank configuration
Configuration config = new Configuration();
// make changes to the configuration
config.CurrentAmplitude.value1 = 123;
config.CurrentAmplitude.value2 = "Hello";
config.FlagClass.flag1 = false;
config.FlagClass.flag2 = true;
// serialize configuration to a string in order to save to a file
string json = JsonConvert.SerializeObject(config);
// reload config from saved string
config = JsonConvert.DeserializeObject<Configuration>(json);
// should print "Hello"
Console.WriteLine(config.CurrentAmplitude.value2);
}
class Configuration
{
public CurrentAmplitude CurrentAmplitude { get; set; } = new CurrentAmplitude();
public FlagClass FlagClass { get; set; } = new FlagClass();
}
class CurrentAmplitude
{
public int value1 { get; set; }
public string value2 { get; set; }
public string value3 { get; set; }
public string value4 { get; set; }
public string value5 { get; set; }
}
class FlagClass
{
public bool flag1 { get; set; }
public bool flag2 { get; set; }
}
Pre C# 6, your config class would look like this:-
class Configuration
{
public Configuration()
{
CurrentAmplitude = new CurrentAmplitude();
FlagClass = new FlagClass();
}
public CurrentAmplitude CurrentAmplitude { get; set; }
public FlagClass FlagClass { get; set; }
}
Related
All - I've stumbled into a scenario that's causing me quite a bit of grief. I have a json structure (produced by gateio api) which on the face of it, looks super simple to deserialize into an object. the jsonTickerString looks like the below:
{
"method":"ticker.update",
"params":[
"BTC_USDT",
{
"period":86400,
"open":"46721.06",
"close":"48130.43",
"high":"48758.59",
"low":"46330.3",
"last":"48130.43",
"change":"2.95",
"quoteVolume":"2246.8399550054",
"baseVolume":"106183751.468785134437"
}
],
"id":null
}
However, this is proving to be deceptively funky when trying to push it into an object model. I derived the object model below and thought we were all set to go:
public partial class GateIoTicker
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamElement> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
}
public class ParamClass
{
[JsonProperty("period")]
public long Period { get; set; }
[JsonProperty("open")]
public string Open { get; set; }
[JsonProperty("close")]
public string Close { get; set; }
[JsonProperty("high")]
public string High { get; set; }
[JsonProperty("low")]
public string Low { get; set; }
[JsonProperty("last")]
public string Last { get; set; }
[JsonProperty("change")]
public string Change { get; set; }
[JsonProperty("quoteVolume")]
public string QuoteVolume { get; set; }
[JsonProperty("baseVolume")]
public string BaseVolume { get; set; }
}
public partial struct ParamElement
{
public string coinName;
public ParamClass quoteParams;
public static implicit operator ParamElement(ParamClass quoteparams)
{
return new ParamElement { quoteParams = quoteparams };
}
public static implicit operator ParamElement(string coinname)
{
return new ParamElement { coinName = coinname };
}
}
I then set about populating the object using the standard Json.Net approach:
var gateIoTicker = JsonConvert.DeserializeObject<GateIoTicker>(jsonTickerString);
However, although this correctly deserializes the string element in the "params" object, no amount of coersion will bring about a deserialization of the ParamClass object.
Am I missing something very obvious here?? I've spent an inordinate amount of time trying to figure this out and think it's now time to solicit some superior brain power.
Hope this scans as expected...
[Edit] - further to Serge's suggestion, i took his code and added it as a method on my GatIoTicker object. Would have preferred an option that desrializes using attributes, but this works perfectly. Refactored code looks like:
public partial class GateIoTicker
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamElement> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
public GateIoTicker FromJson(string json)
{
var jsonObject = JObject.Parse(json);
var pars = jsonObject["params"] as JArray;
var paramElement = new ParamElement();
foreach (var jObject in pars)
{
if (jObject.GetType().Name.ToString() == "JValue") paramElement.ParamName = ((JValue)jObject).ToString();
else
{
paramElement.ParamBody = jObject.ToObject<ParamClass>();
}
}
GateIoTicker gateIoTicker = new GateIoTicker { Params = new List<ParamElement>() };
gateIoTicker.Id = (string)jsonObject["Id"];
gateIoTicker.Method = (string)jsonObject["method"];
gateIoTicker.Params.Add(paramElement);
return gateIoTicker;
}
}
public partial class ParamElement
{
public string ParamName { get; set; }
public ParamClass ParamBody {get; set;}
}
thanks again for the suggestions and nudges. seasons greetings
Try this, it was tested in Visual studio
var jsonObject = JObject.Parse(json);
var pars = jsonObject["params"] as JArray;
var paramElement = new ParamElement();
foreach (var jObject in pars)
{
if (jObject.GetType().Name.ToString() == "JValue") paramElement.ParamName = ((JValue)jObject).ToString();
else
{
paramElement.ParamBody=jObject.ToObject<ParamClass>();
}
}
GateIoTicker gateIoTicker = new GateIoTicker {Params= new List<ParamElement>()};
gateIoTicker.Id= (string) jsonObject["Id"];
gateIoTicker.Method= (string) jsonObject["method"];
gateIoTicker.Params.Add(paramElement);
ParamElement class
public partial class ParamElement
{
public string ParamName { get; set; }
public ParamClass ParamBody {get; set;}
}
I have a json object that I need to deserialize, I'm using Json.NET to make these operations.
when it's a simple object, its quite easy to do it, but I cant figure out how to deserialize this string
json
{
"aspsp-list":
[
{
"id":"424250495054504C",
"bic":"BBPIPTPL",
"bank-code":"0010",
"aspsp-cde":"BBPI",
"name":"BANCO BPI, SA",
"logoLocation":"../img/corporate/theBank.jpg",
"api-list":[{
"consents":["BBPI/v1/consents"],
"payments":["BBPI/v1/payments"],
"accounts":["BBPI/v1/accounts"],
"funds-confirmations":["BBPI/v1/funds-confirmations"]
}]
},
{
"id":"544F54415054504C",
"bic":"TOTAPTPL",
"bank-code":"0018",
"aspsp-cde":"BST",
"name":"BANCO SANTANDER TOTTA, SA",
"logoLocation":"../img/openBank.svc",
"api-list":[{
"consents":["BBPI/v1/consents"],
"payments":["BBPI/v1/payments"],
"accounts":["BBPI/v1/accounts"],
"funds-confirmations":["BST/v1/funds-confirmations"]
}]
}
]
}
Now the code I have so far:
internal class AspspListResponseResource
{
// Report with the list of supported ASPSPs. Each ASPSP will include the list of available API endpoints and the logo.
[JsonProperty(PropertyName = "aspsp-list")]
public AspspList[] AspspList { get; set; }
public AspspListResponseResource() { /* Empty constructor to create the object */ }
public AspspListResponseResource(string jsonString)
{
//var alrr = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
JObject jObject = JObject.Parse(jsonString);
JToken jUser = jObject["aspsp-list"];
// The root object here is coming with certain fields as null, such as 'aspsp-cde', 'bank-code' and 'api-list'
AspspListResponseResource root = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
}
}
internal class Aspsp
{
// ASPSP Id
[JsonProperty(PropertyName = "id")]
public string Id { get; set; } = "";
// Bank Identifier Code
[JsonProperty(PropertyName = "bic")]
public string Bic { get; set; } = "";
// IBAN Bank Identifier
[JsonProperty(PropertyName = "bank-code")]
public string BankCode { get; set; } = "";
// ASPSP Code to use in the endpoint
[JsonProperty(PropertyName = "aspsp-cde")]
public string AspspCde { get; set; } = "";
// Institution name
[JsonProperty(PropertyName = "name")]
public string Name { get; set; } = "";
// Bank logo location
[JsonProperty(PropertyName = "logoLocation")]
public string LogoLocation { get; set; } = "";
// Bank Supported API List
[JsonProperty(PropertyName = "api-list")]
public ApiLink[] ApiList { get; set; }
}
internal class ApiLink
{
// Consents Link List
[JsonProperty(PropertyName = "consents")]
public string[] Consents { get; set; } = { "" };
// Payments Link List
[JsonProperty(PropertyName = "payments")]
public string[] Payments { get; set; } = { "" };
// Accounts Link List
[JsonProperty(PropertyName = "accounts")]
public string[] Accounts { get; set; } = { "" };
// Balances Link List
[JsonProperty(PropertyName = "balances")]
public string[] Balances { get; set; } = { "" };
// Transaction Link List
[JsonProperty(PropertyName = "transaction")]
public string[] Transaction { get; set; } = { "" };
// Funds-Confirmations Link List
[JsonProperty(PropertyName = "funds-confirmations")]
public string[] FundsConfirmations { get; set; } = { "" };
}
Sum of the values of the deserialized object are null, even though the jsonString definitelly has data.
How should I proceed here?
The way your json is structured:
{
"aspsp-list":
[
{
"id":"123123123",
"bic":"BBPIPTPL",
"bank-code":"0010",
"aspsp-cde":"BBPI",
"name":"BANCO BPI, SA",
"logoLocation":"../img/corporate/theBank.jpg",
"api-list":[{
"consents":"",
"payments":"",
"accounts":"",
"funds-confirmations":""
}]
},
{
"id":"1434231231",
"bic":"TOTAPTPL",
"bank-code":"0018",
"aspsp-cde":"BST",
"name":"BANCO SANTANDER TOTTA, SA",
"logoLocation":"../img/openBank.svc",
"api-list":[{
"consents":"",
"payments":"",
"accounts":"",
"funds-confirmations":""
}]
}
]
}
This is telling us that you have an object, with an array of objects called Aspsp-list.
If this is what you intended great.
We need to create an object similar to this
public class RootJsonObject {
public IEnumerable<Aspsp> Aspsp-list {get; set;}
}
To deserialize to this simply:
JsonConvert.Deserialize<RootJsonObject>(/*your json string*/ value);
If you wanted to only work with the array, you would need to deserialize purely to an IEnumerable/Array But you would also need to change your json to just be an array, not an object wrapping an array.
I managed to make it work now, my problem wasn't exactly that I couldn't deserialize because of data types or structure (at least not completely, comment that said that the structure was wrong was partly right).
So, this is how I solved the problem:
-> Created an empty costructor on the AspspListResponseResource class, so that the method JsonConvert.DeserializeObject<T>(jsonString) could create an instance of the object, I thought of this since the only constructor took a string, and so there was no other contructor for JsonConvert to use.
-> Put the field names of with help of [JsonProperty(PropertyName = "")], but this still gave me the deserialized object as null, or with some null fields.
-> commented the fields Transaction and FundsConfirmations of the ApiLink class, these fields were in the documentation of the Web API so I put them in, but looking at the json string I recieve, it look like they aren't being used, so I just commented them
and after these changes the code now works flawlessly:
The code:
internal class AspspListResponseResource
{
// Report with the list of supported ASPSPs. Each ASPSP will include the list of available API endpoints and the logo.
[JsonProperty(PropertyName = "aspsp-list")]
public Aspsp[] AspspList { get; set; }
public AspspListResponseResource() { /* Empty constructor to create the object */ }
public AspspListResponseResource(string jsonString)
{
AspspListResponseResource root = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
this.AspspList = root.AspspList;
}
}
internal class Aspsp
{
// ASPSP Id
[JsonProperty(PropertyName = "id")]
public string Id { get; set; } = "";
// Bank Identifier Code
[JsonProperty(PropertyName = "bic")]
public string Bic { get; set; } = "";
// IBAN Bank Identifier
[JsonProperty(PropertyName = "bank-code")]
public string BankCode { get; set; } = "";
// ASPSP Code to use in the endpoint
[JsonProperty(PropertyName = "aspsp-cde")]
public string AspspCde { get; set; } = "";
// Institution name
[JsonProperty(PropertyName = "name")]
public string Name { get; set; } = "";
// Bank logo location
[JsonProperty(PropertyName = "logoLocation")]
public string LogoLocation { get; set; } = "";
// Bank Supported API List
[JsonProperty(PropertyName = "api-list")]
public ApiLink[] ApiList { get; set; }
}
internal class ApiLink
{
// Consents Link List
[JsonProperty(PropertyName = "consents")]
public string[] Consents { get; set; } = { "" };
// Payments Link List
[JsonProperty(PropertyName = "payments")]
public string[] Payments { get; set; } = { "" };
// Accounts Link List
[JsonProperty(PropertyName = "accounts")]
public string[] Accounts { get; set; } = { "" };
// Balances Link List
[JsonProperty(PropertyName = "balances")]
public string[] Balances { get; set; } = { "" };
//// Transaction Link List
//[JsonProperty(PropertyName = "transaction")]
//public string[] Transaction { get; set; } = { "" };
//
//// Funds-Confirmations Link List
//[JsonProperty(PropertyName = "funds-confirmations")]
//public string[] FundsConfirmations { get; set; } = { "" };
}
You need to create a contructor for the ApiLink class so you can do the following:
var apiListRaw = new ApiLink(value["api-list"][0] as JObject);
The constructor would look something like the following:
public ApiLink(JObject json)
{
Consensts = (string[])json["consents"];
...
}
So i'm getting a response like this
{"$id":"1","success":true,"errors":{"$id":"2","$values":[]}}
how can i convert this into to a c# object, tried using this(http://json2csharp.com/) tool to make an output but it doesn't make sense
this is what i'm getting
x
public class Errors
{
public string __invalid_name__$id { get; set; }
public List<object> __invalid_name__$values { get; set; }
}
public class RootObject
{
public string __invalid_name__$id { get; set; }
public bool success { get; set; }
public Errors errors { get; set; }
}
I'm kinda new to c#, any inputs would be deeply appreciated, i basically need access to success key variable
You need to add [JsonProperty] attribute to every property that key name started with dollar $
public class Errors
{
[JsonProperty("$id")]
public string id { get; set; }
[JsonProperty("$values")]
public List<object> values { get; set; }
}
public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public bool success { get; set; }
public Errors errors { get; set; }
}
Because the $ indicates metadata, not an actual data field. so you have to modify your JsonSerializerSettings to ignore MetadataPropertyHandling.
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
And finally deserialize your json to above class objects.
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json, settings);
Here I created a sample console app for demonstration purpose that shows how above code will work.
class program
{
public static void Main()
{
string json = File.ReadAllText(#"Path to your json file");
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json, settings);
Console.WriteLine("id: " + rootObject.id);
Console.WriteLine("success: " + rootObject.success);
Console.WriteLine("errors.id: " + rootObject.errors.id);
Console.WriteLine("errors.values: " + string.Join(",", rootObject.errors.values));
Console.ReadLine();
}
}
Output:
Well, What you can do is
public class Errors
{
[JsonProperty(PropertyName = "$id")]
public string id { get; set; }
[JsonProperty(PropertyName = "$values")]
public List<object> values { get; set; }
}
public class RootObject
{
[JsonProperty(PropertyName = "$id")]
public string id { get; set; }
public bool success { get; set; }
public Errors errors { get; set; }
}
You need your object attributes to match you json string ($id instead of _invalid_name_$id), then you can use:
JsonConvert.DeserializeObject<RootObject>(jsonString);
Here is a simple class to serialize json string from object or to object (T). May de/serialize array(list) of objects.
public class HelperSerializer<T> where T: class
{
public static string WriteFromObject(T source)
{
using (var ms = new MemoryStream()) {
var ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(ms, source);
byte[] json = ms.ToArray();
return Encoding.UTF8.GetString(json, 0, json.Length);
}
}
// Deserialize a JSON stream to an object.
public static T ReadToObject(string json)
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var ser = new DataContractJsonSerializer(typeof(T));
return ser.ReadObject(ms) as T;
}
}
}
Use persons = HelperSerializer<List<Person>>.ReadToObject(json);
and var json = HelperSerializer<List<Person>>.WriteFromObject(persons);
I'm using Newwtonsoft.JSON for build my json file, actually what I did is create different classes models, as this:
class GeneralModel
{
public string Language { get; set; }
}
and then for build the json file:
GeneralModel lsModel = new GeneralModel();
string json = JsonConvert.SerializeObject(lsModel);
File.WriteAllText(settingsFilePath, json);
this will create a json that contains Language, but I need to put in this json different classes, what I need is set an index that contains each class name, for example:
"GeneralModel": {
"Language" : "english"
},
"AnoherClassName": {
"ClassProperty" : value
}
how can I do this with Newtonsoft?
public class GeneralModel
{
public string Language { get; set; }
}
public class AnotherModel
{
public string AnotherProperty { get; set; }
}
public class SuperClass
{
public GeneralModel generalModel { get; set; }
public AnotherModel anotherModel { get; set; }
}
then
SuperClass s = new WMITest.SuperClass();
s.generalModel = new GeneralModel();
s.generalModel.Language = "language";
s.anotherModel = new AnotherModel();
s.anotherModel.AnotherProperty = "example";
string json = JsonConvert.SerializeObject(s);
I try to deserialization a JSON like the following(Numbers like 93817 and 935812 are dynamically generated from a server. Can't be hard coded.):
{ "status":"1",
"list":{
"93817":{ "item_id":"93817",
"url":"http://url.com",
"title":"Page Title",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"0"
},
"935812":{ "item_id":"935812",
"url":"http://google.com",
"title":"Google",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"1"
} }}
Here is the code for deserialization:
responseGetList = e.Result.ToString(); //responseGetList is the JSON string
MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes(responseGetList));
DataContractJsonSerializer serializer =
new DataContractJsonSerializer( typeof(List<ResponseItem>) );
ResponseItem li = (ResponseItem)serializer.ReadObject(ms);
And the following is the ResponseItem class:
namespace whatever
{
[DataContract]
public class ResponseItem
{
[DataMember(Name = "status")]
string status;
public string Status
{
get { return status; }
set { status = value; }
}
[DataMember(Name = "list")]
List<ListItem> list;
private List<ListItem> List
{
get { return list; }
set { list = value; }
}
}
public class ListItem
{
[DataMember]
List<Article> listArticle;
public List<Article> ListArticle
{
get { return listArticle; }
set { listArticle = value; }
}
}
}
public class Article
{
[DataMember(Name = "item_id")]
string item_id;
public string Item_id
{
get { return item_id; }
set { item_id = value; }
}
[DataMember(Name = "url")]
string url;
public string Url
{
get { return url; }
set { url = value; }
}
[DataMember(Name = "title")]
string title;
public string Title
{
get { return title; }
set { title = value; }
}
[DataMember(Name = "time_updated")]
string time_updated;
public string Time_updated
{
get { return time_updated; }
set { time_updated = value; }
}
[DataMember(Name = "time_added")]
string time_added;
public string Time_added
{
get { return time_added; }
set { time_added = value; }
}
[DataMember(Name = "tags")]
string tags;
public string Tags
{
get { return tags; }
set { tags = value; }
}
[DataMember(Name = "state")]
string state;
public string State
{
get { return state; }
set { state = value; }
}
}
I get InvalidCastException on 1ataContractJsonSerializer serializer =
new DataContractJsonSerializer( typeof(List<ResponseItem>) );, I think it is a JSON-Object mapping problem. Can any one help me?
Try using NewtonSoft's LINQ to Json, it's a way cleaner method to de/serialize json strings
ClassName class= new ClassName();
objectname = JsonConvert.DeserializeObject<ClassName>(responseGetList);
Use Json2C# to create the ClassName you need to have to be able to deserialize straight into an object.
You can use object.__ to call upon any of the results: example with your code:
object.list.(93817(you will have to cast this with a JsonProperty, because c# doesn't allow methods with solely numbers)).item_id = 93817
cleaner : object.list.thenameyougavethemethod.item_id
Good luck, if you have more questions, just add comments
EDIT : I parsed the json string and added JsonProperties to your specific Json String;
Just download the NewtonSoft .dll & don't forget to add a reference to your project ...
public class id93817
{
public string item_id { get; set; }
public string url { get; set; }
public string title { get; set; }
public string time_updated { get; set; }
public string time_added { get; set; }
public string tags { get; set; }
public string state { get; set; }
}
public class id935812
{
public string item_id { get; set; }
public string url { get; set; }
public string title { get; set; }
public string time_updated { get; set; }
public string time_added { get; set; }
public string tags { get; set; }
public string state { get; set; }
}
public class List
{
[JsonProperty("93817")]
public id93817 { get; set; }
[JsonProperty("935812")]
public id935812 { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List list { get; set; }
}
Try switching to Json.NET for deserializing the object. It is less error prone and fragile (and yes, it's open source and works on the phone)>
The first item in the lists are incorrect. Your JSON shows "93817" and "935812" but those are not properties on your items. The first part of your JSON must be a property name. You're doing it right for "list" because it corresponds to the List property of ResponseItem. Change those numbers to "listArticle". I also second Shawn Wildermuth's suggestion for JSON.Net.
The JSON that is generated on the server should be serialized the same way that it is deserialized (ie: use the same framework to (de)serialize). If you are generating the JSON by hand, don't. You will have more problems than you need or want.
If you serialize the object, you should have the following:
{ "status":"1",
"list":{
"listArticle":{
"item_id":"93817",
"url":"http://url.com",
"title":"Page Title",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"0"
},
"listArticle":{
"item_id":"935812",
"url":"http://google.com",
"title":"Google",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"1"
}
}
}
Issue resolved by reading the source code of RIL# (http://rilsharp.codeplex.com/).
The problem is mainly mapping issue. Using Dictionary is the key resolution:
[DataContract]
public class ResponseItem
{
[DataMember(Name = "status")]
public ListStatus Status { get; set; }
[DataMember(Name = "since")]
public double Since { get; set; }
[DataMember(Name = "list")]
public Dictionary<string, RilListItem> items { get; set; }
public DateTime SinceDate
{
get
{
return UnixTime.ToDateTime(Since);
}
}
Then using Json.net to deserialize the JSON:
ResponseItem ri = new ResponseItem();
ri = JsonConvert.DeserializeObject<ResponseItem>(responseGetList);