0

I am trying to get some currency values from an api. it's returning the data in the following format:

{"PKR_PKR":{"val":1}}

I want to show this value in textbox but there's an error

"Object reference not set to an instance of object".

I've tried the following code:

try
{
    string endPoint = @"http:urlhere";
    string ResultJson = "";

    using (WebClient wc = new WebClient())
    {
        ResultJson = wc.DownloadString(endPoint);
    }
    JsonData values = JsonConvert.DeserializeObject<JsonData>(ResultJson); 
    txtBalanceRate.Text = values.CurrencyValue.ToString();
}
catch (Exception ex) { }

Class code:

class JsonData
{
    public object CurrencyValue { get; set; }
}

**

  • UPDATE

**

Note: I can not update PKR_PKR Class becuase every time the name of variable is different for different currencies i.e. it can be USD_PKR , EUR_PKR etc How can I resolve this?

FOLLOWING IS THE UPDATED CODE:

 try
            {
               string endPoint = @"http://free.currencyconverterapi.com/api/v5/convert?q="+ddlCurrency.SelectedValue.ToString()+"_PKR&compact=y";
               string ResultJson = "";

                using (WebClient wc = new WebClient())
                {
                    ResultJson = wc.DownloadString(endPoint);
                }

                RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(ResultJson);                

                txtBalanceRate.Text = rootObject.PKR_PKR.val.ToString();          



            }
            catch (Exception ex)
            {

            }

public class PKRPKR
{
    public int val { get; set; }
}

public class RootObject
{
    public PKRPKR PKR_PKR { get; set; }
}
Alina Anjum
  • 1,178
  • 6
  • 30
  • 53
  • The JSON has no relation to the `JsonData` class. Either create a *matching* class or use JObject.Parse and access the individual properties – Panagiotis Kanavos May 28 '18 at 07:30
  • How can I do this please help. – Alina Anjum May 28 '18 at 07:31
  • PS remove the `Catch(Exception ex){}` block. The only thing it does is ensure your program will crash with a really weird error when eg you try sell using a currency value of 0 – Panagiotis Kanavos May 28 '18 at 07:31
  • Possible duplicate of [Parsing JSON key/value pairs with JSON.NET](https://stackoverflow.com/questions/29632593/parsing-json-key-value-pairs-with-json-net) – smile May 28 '18 at 07:58

3 Answers3

3

If you are going to have dynamic object then you should try this out

   dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
   Type typeOfDynamic = data.GetType();
   if( typeOfDynamic.GetProperties().Where(p => p.Name.Equals("PKR_PKR")).Any())
   {
     console.WriteLine(data.PKR_PKR.val); 
   }
   else if( typeOfDynamic.GetProperties().Where(p => p.Name.Equals("USD_PKR")).Any())
   {
     console.WriteLine(data.USD_PKR.val); 
   }
else if( typeOfDynamic.GetProperties().Where(p => p.Name.Equals("EUR_PKR")).Any())
   {
     console.WriteLine(data.EUR_PKR.val); 
   }

above way is not tried and tested but you can have try like this as you json is dynamic.

Above way is checking property exist or not and get val from dynamci object


Your class structure is incorrect can you please try below class structure

public class PKRPKR
{
    public int val { get; set; }
}

public class RootObject
{
    public PKRPKR PKR_PKR { get; set; }
}

RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(rootObject.PKR_PKR.val);

Mostly if you see above class structure , you josn each node is represent as class, but I dont go in much detail as Visual studio can do it for me.

When comes to json to object conversion ,I make use of utility provided by Visual studio. which does conversion of json string to proper class structure. here is image of it

enter image description here

Read how to do it full here :
Visual Studio Generate Class From JSON or XML

If you dont have visual studio with this feature you can use this online utility : json2csharp

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

I think your receiving object should contain a dictionary, not a single string:

Check this

Or you have to improve your object structure implementing a root item which contains a PKR_PKR sub object

Community
  • 1
  • 1
Liquid Core
  • 1
  • 6
  • 27
  • 52
0

Note: I can not update PKR_PKR Class becuase evert time the name of variable is different for different currencies i.e. it can be USD_PKR , EUR_PKR etc How can I resolve this?

SOLUTION

if json string {"PKR_PKR":{"val":1}} is fixed in your case, you can use following solution for any currency name you got.

static void Main(string[] args)
{
    string json1 = "{ \"PKR_PKR\":{ \"val\":1}}";

    string json2 = "{ \"USD_PKR\":{ \"val\":2}}";

    string json3 = "{ \"EUR_PKR\":{ \"val\":3}}";


    JToken token1 = (JToken)JsonConvert.DeserializeObject(json1);
    Console.WriteLine(token1.First().First()["val"]);


    JToken token2 = (JToken)JsonConvert.DeserializeObject(json2);
    Console.WriteLine(token2.First().First()["val"]);

    JToken token3 = (JToken)JsonConvert.DeserializeObject(json3);
    Console.WriteLine(token3.First().First()["val"]);


    Console.ReadLine();
}
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34