getting object property value from json response in c# - c#

I am trying to access the "success" property to get its value. Right now, it is hitting catch saying "Object reference not set to an instance of an object. " How do I get the string value?
{ "success": true, "next": "/locations", "amount": 325, "keys": 3,
"credits": 6185}
private static void postComplete(object sender, UploadStringCompletedEventArgs e)
{
object result = JsonConvert.DeserializeObject<object>(e.Result);
try{
PropertyInfo pi = result.GetType().GetProperty("success");
String success = (String)(pi.GetValue(result, null));
Console.Write(success);
}
catch (Exception f) {
Console.Write(f);
}

You're deserializing it as a straight up object.. object doesn't have a property named success.
The alternative is to type a class that represents this:
class ExampleClass {
public bool success { get; set; }
public string next { get; set; }
public int amount { get; set; }
public int keys { get; set; }
public int credits { get; set; }
}
Then call it like this:
object result = JsonConvert.DeserializeObject<ExampleClass>(e.Result);
// ^^^^^^^^^^^^
// This
try{
PropertyInfo pi = result.GetType().GetProperty("success");
bool success = (bool)(pi.GetValue(result, null));
Console.Write(success); // True
}
catch (Exception f) {
Console.Write(f);
}
Or even better.. remove that altogether:
ExampleClass example = JsonConvert.DeserializeObject<ExampleClass>(e.Result);
Console.WriteLine(example.success); // True

Related

Problems with deserializing FieldInfos and PropertyInfos when using Newtonsoft.Json libraries

I am trying to serialize and deserialize FieldInfo and PropertyInfos, and I am getting this error, which I dont understand, nor do I know how to fix or change what I am doing to fix this: Newtonsoft.Json.JsonSerializationException: Could not create an instance of type System.Reflection.FieldInfo. Type is an interface or abstract class and cannot be instantiated.
The basis of what I am trying to do is serialize and deserialize a class called AutoLType that looks like this:
public class AutoLType
{
public static implicit operator AutoSType(AutoLType l)
{
if (l.PropertyOrField == PropOrField.Field)
{
return new AutoSType(l.Field, l.Attribute, AutoSType.PropOrField.Field);
}
else
{
return new AutoSType(l.Property, l.Attribute, AutoSType.PropOrField.Prop);
}
}
public enum PropOrField
{
Prop,
Field
}
public PropertyInfo Property { get; set; }
public FieldInfo Field { get; set; }
public AutoLoad Attribute { get; set; }
public PropOrField PropertyOrField { get; set; }
public AutoLType(object pOrF, AutoLoad attr, PropOrField propOrField)
{
if (pOrF is PropertyInfo)
{
Property = (PropertyInfo)pOrF;
}
else if(pOrF is FieldInfo)
{
Field = (FieldInfo)pOrF;
}
Attribute = attr;
PropertyOrField = propOrField;
}
}
public AutoLType Load(AutoLType autoLTypeToLoad)
{
AutoLType a = null;
try
{
string filePath = Application.persistentDataPath + autoLTypeToLoad.Attribute.FilePath;
string json = File.ReadAllText(filePath);
a = JsonConvert.DeserializeObject<AutoLType>(json);
}
catch (Exception ex)
{
Debug.Log(ex.ToString());
}
return a;
}
Let me know if you need to see the AutoLoad class, but it isnt giving any problems right now.

JSON to List<class> & List<class> to JSON?

Hi guys how do I get this to work? I searched in SO and this was the most promissing but it doesnt work either.
errormessage:
The deserialized type should be a normal .NET type (i.e. not a
primitive type like integer, not a collection type like an array or
List) or a dictionary type (i.e. Dictionary).
so how do i split the individual objects from my json?
List<class> a = JsonConvert.DeserializeObject<List<class>>(JSON_String)
the JSON string:
{
"SPALTEN": [{
"NUMMER": 1,
"NAME": "BREITE",
"TYP": "Double",
"LAENGE": 0,
"EINHEIT": "m",
"EDITIERBAR": true,
"OPTIONAL": true,
"LAYER": null,
"LAYER_SPALTE": null,
"D_SPAL_NAME": null,
"D_SPAL_MIN": 0,
"D_SPAL_MAX": null,
"D_SPAL_VAL": null
}, {
"NUMMER": 2,
"NAME": "KOMMENTAR",
"TYP": "String",
"LAENGE": 255,
"EINHEIT": null,
"EDITIERBAR": true,
"OPTIONAL": true,
"LAYER": null,
"LAYER_SPALTE": null,
"D_SPAL_NAME": null,
"D_SPAL_MIN": null,
"D_SPAL_MAX": null,
"D_SPAL_VAL": null
}]
}
here is my class:
public class CONFIG_CLASS
{
private int _NUMMER;
public int NUMMER
{
get { return _NUMMER; }
set { _NUMMER = value; }
}
private string _NAME;
public string NAME
{
get { return _NAME; }
set { _NAME = value; }
}
private string _TYP;
public string TYP
{
get { return _TYP; }
set { _TYP = value; }
}
private double _LAENGE;
public double LAENGE
{
get { return _LAENGE; }
set { _LAENGE = value; }
}
private string _EINHEIT;
public string EINHEIT
{
get { return _EINHEIT; }
set { _EINHEIT = value; }
}
private bool _EDITIERBAR;
public bool EDITIERBAR
{
get { return _EDITIERBAR; }
set { _EDITIERBAR = value; }
}
private bool _OPTIONAL;
public bool OPTIONAL
{
get { return _OPTIONAL; }
set { _OPTIONAL = value; }
}
private string _LAYER;
public string LAYER
{
get { return _LAYER; }
set { _LAYER = value; }
}
private int _LAYER_SPALTE;
public int LAYER_SPALTE
{
get { return _LAYER_SPALTE; }
set { _LAYER_SPALTE = value; }
}
private string _D_SPAL_NAME;
public string D_SPAL_NAME
{
get { return _D_SPAL_NAME; }
set { _D_SPAL_NAME = value; }
}
private int _D_SPAL_MIN;
public int D_SPAL_MIN
{
get { return _D_SPAL_MIN; }
set { _D_SPAL_MIN = value; }
}
private int _D_SPAL_MAX;
public int D_SPAL_MAX
{
get { return _D_SPAL_MAX; }
set { _D_SPAL_MAX = value; }
}
private string _D_SPAL_VAL;
public string D_SPAL_VAL
{
get { return _D_SPAL_VAL; }
set { _D_SPAL_VAL = value; }
}
}
(I would also like to encode it again later)
thank you!
You should specify the type of thing you want to deserialise, I don't think object will work.
List<MyClass> a = JsonConvert.DeserializeObject<List<MyClass>>("[{some json}]")
Sorry I cannot put comments yet
First,you have some type mismatch between your data and your convert class:
LAYER_SPALTE, D_SPAL_MIN and D_SPAL_MAX are null in your data.
put try putting your array inside another class
this code has to work for you:
public class MyClass
{
public SPALTEN[] SPALTEN { get; set; }
}
public class SPALTEN
{
public int NUMMER { get; set; }
public string NAME { get; set; }
public string TYP { get; set; }
public int LAENGE { get; set; }
public string EINHEIT { get; set; }
public bool EDITIERBAR { get; set; }
public bool OPTIONAL { get; set; }
public string LAYER { get; set; }
public int? LAYER_SPALTE { get; set; }
public string D_SPAL_NAME { get; set; }
public int? D_SPAL_MIN { get; set; }
public int? D_SPAL_MAX { get; set; }
public string D_SPAL_VAL { get; set; }
}
and then
MyClass a = JsonConvert.DeserializeObject<MyClass>(JSON_String)
To convert it on Internet, you can use the below URL for JSON to C#. I have been using from so long.
http://json2csharp.com/

c# null value after deserialize

I have a problem with deserialization.
It's my json structure
{ "status": "ok",
"data": [
{
"issued": 1447358848072,
"volume": "5.52565454",
"currency": "pln",
"limit": "724.2500",
"type": "bid",
"id": "2015/11/12/13328345/4836"
},
{
"issued": 1447359927423,
"volume": "1.25465440",
"currency": "pln",
"limit": "1850.5000",
"type": "ask",
"id": "2015/11/12/13328342/8188"
}
]
}
It's my class in C# and functions:
public class oferta
{
public string issued { get; set; }
public string volume { get; set; }
public string currency { get; set; }
public string limit { get; set; }
public string type { get; set; }
public string id { get; set; }
}
public class tBitCurex_PRV_Offers
{
public string status { get; set; }
public List<oferta> data { get; set; }
}
public void GetPRV_Offers(tBitCurex_PRV_Offers B)
{
try
{
var RSP = "my json string";
B = JsonConvert.DeserializeObject<tBitCurex_PRV_Offers>(RSP);
if (B.data.Count > 0)
{
// in here COUNT = 2 and all works fine.
// and B.status = "ok"
// but when function is end i have a null
}
}
catch (Exception oException)
{
MessageBox.Show(oException.Message);
}
}
public void Pobierz_PRV_Offers()
{
try
{
var BitCurexOfers = new tBitCurex_PRV_Offers();
GetPRV_Offers(BitCurexOfers);
if (BitCurexOfers.status == "ok")
{
// do something with BitcurexOffers;
// I have a NULL if a use deserialize.
}
}
catch
{
sbInfo2.Text = "Error..xxxx";
}
finally
{
Application.DoEvents();
}
}
When in similar fuction i use
JObject oObject = JObject.Parse("json string");
B.status = (string)oObject["status"];
then all works fine inside and outside the function.
How should i do this properly with JsonConvert.DeserializeObject ???
Your problem is not with deserialization but with reference pointers
Instead of void, change the return type of the Function to BitCurex_PRV_Ofers and at the end of the function return B; and assign BitCurexOfers to the result of the function call instead of instantiating a new instance
Or just change the parameter to
ref BitCurex_PRV_Ofers B)
This is happening because you get a pointer to BitCurexOfers in B, then change that pointer with the result of deserialization
If you use JsonConvert.Poupulate(B); this will also work for you without any other changes
Your problem is that you're not altering B in the caller, just the method in which you're doing the deserialization. You can either change B to a ref parameter, or you can return it from the method instead.
Your sample code has some errors. try adding this attribute and it should work.
[Newtonsoft.Json.JsonObject(Title = "root")]
public class tBitCurex_PRV_Offers

Get data from Json file C#

I have this Json file:
{"id":88319,"dt":1345284000,"name":"Benghazi",
"coord":{"lat":32.12,"lon":20.07},
"main":{"temp":306.15,"pressure":1013,"humidity":44,"temp_min":306,"temp_max":306},
"wind":{"speed":1,"deg":-7},
"weather":[
{"id":520,"main":"rain","description":"light intensity shower rain","icon":"09d"},
{"id":500,"main":"rain","description":"light rain","icon":"10d"},
{"id":701,"main":"mist","description":"mist","icon":"50d"}
],
"clouds":{"all":90},
"rain":{"3h":3}}
I can read the "name": "Benghazi" normally but the "temp":306.15 I can not read because it is inside "main":{}
I'm using a simple way to read, here is my C# code:
public class SkyWeather
{
string path = #"http://api.openweathermap.org/data/2.5/weather?q=Uberaba,br&units=metric";
string name;
string temp;
public string Name { get { return name; } set { name = value; } }
public string Temp { get { return temp; } set { temp = value; } }
public string GetTemperature()
{
var json = "";
try
{
json = new WebClient().DownloadString(path);
}
catch (Exception e)
{
return e.ToString();
}
string text = (string)json;
SkyWeather w = JsonConvert.DeserializeObject<SkyWeather>(text);
return w.temp;
}
}
How can I read it?
Assuming that SkyWeather represents the properties in your "main" object, you'll need to create another object that represents the wrapping object:
public class RootObject
{
public int id { get; set; }
public int dt { get; set; }
public string name { get; set; }
public SkyWeather main { get; set; }
}
... and then:
RootObject w = JsonConvert.DeserializeObject<RootObject>(text);
return w.main.temp;

WP7 JSON returning list within a list

I'm trying to return json data from a list within a list. The data is being pulled using a webclient and deserialized using JSON.NET. I'd like to return a name and image from the "featuredCharts" list which is within the "Results" list. Here is part of the json data I'm referring to.
"results":{
"featuredCharts":[
{
"id":46082,
"type":"chart",
"name":"Exclusives On Beatport - Week 5",
"slug":"exclusives-on-beatport-week-5",
"description":"",
"publishDate":"2012-01-30",
"price":{
"code":"usd",
"symbol":"$",
"value":2390
},
"audioFormatFee":{
"wav":{
"code":"usd",
"symbol":"$",
"value":1000
},
"aiff":{
"code":"usd",
"symbol":"$",
"value":1000
}
},
"genres":[
{
"id":11,
"name":"Tech House",
"slug":"tech-house",
"type":"genre"
},
{
"id":5,
"name":"House",
"slug":"house",
"type":"genre"
},
{
"id":17,
"name":"Electro House",
"slug":"electro-house",
"type":"genre"
},
{
"id":15,
"name":"Progressive House",
"slug":"progressive-house",
"type":"genre"
}
],
"images":{
"small":{
"width":30,
"height":30,
"url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951247.jpg",
"secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951247.jpg"
},
"medium":{
"width":60,
"height":60,
"url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951248.jpg",
"secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951248.jpg"
},
"large":{
"width":130,
"height":130,
"url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951249.jpg",
"secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951249.jpg"
},
"xlarge":{
"width":500,
"height":500,
"url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/50\/4951250.jpg",
"secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/50\/4951250.jpg"
}
},
"chartOwner":null
},
My classes are currently setup like this.
public class NewReleasesCharts //Root Object
{
public Metadata metadata { get; set; }
public List<ResultHome> results = new List<ResultHome>();
public IEnumerator<ResultHome> GetEnumerator()
{
return this.results.GetEnumerator();
}
}
public class ResultHome
{
public List<FeaturedCharts> featuredCharts { get; set; }
public List<FeaturedReleases> featuredReleases { get; set; }
}
public class FeaturedCharts
{
public int id { get; set; }
public string type { get; set; }
public string name { get; set; }
public string slug { get; set; }
public ChartImages chartImages { get; set; }
}
public class ChartImages
{
public ChartSmall chartSmall { get; set; }
public ChartMedium chartMedium { get; set; }
public ChartLarge chartLarge { get; set; }
}
public class ChartMedium
{
public int width { get; set; }
public int height { get; set; }
public string url { get; set; }
public string secureUrl { get; set; }
}
This is the part I'm stuck on. After deserializing the data I thought about using nested foreach loops, but i currently get an error "Cannot convert type Beatport.Classes.ResultHome' to 'Beatport.Classes.FeaturedCharts". Here is the code.
UPDATE I updated my code per ColinE's answer and I am now getting a NullReferenceException error on the inner foreach loop.
// Deserialize home page data
void jsonHome_GetDataCompleted(object snder, DownloadStringCompletedEventArgs e)
{
try
{
NewReleasesCharts homeData = JsonConvert.DeserializeObject<NewReleasesCharts>(e.Result);
try
{
// Nested foreach loops to dispaly data
foreach (ResultHome rc in homeData)
{
try
{
foreach (FeaturedCharts fc in rc.featuredCharts)
{
// TODO: return name and image of chart
string name = fc.name;
listCharts.Items.Add(name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm still a beginner when it comes to c# so i'm not sure if the nested foreach loops is the right way to go. An example of how to do this properly would give me something to build off of, as i'll need to do this in other parts of my app.
Thanks.
Your second for loop is iterating over the same data as the first. You need to iterate over the featuredCharts property of the variable being iterated in the outer loop:
try
{
NewReleasesCharts homeData = JsonConvert.DeserializeObject<NewReleasesCharts>(e.Result);
// foreach loop to dispaly data
foreach (ResultHome rc in homeData)
{
foreach (FeaturedCharts fc in rc.featuredCharts)
{
// return name and image of chart
}
}
}
To solve this kind of problem in the feature, try setting breakpoints in your code and running in debug mode. You can then inspect the type of each variable to determine what you have done wrong.

Categories

Resources