Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'Newtonsoft.Json.Linq.JToken' to 'string'. An explicit conversion exists (are you missing a cast?)

Tags:

json

c#

.net

I have the following code:

WebClient c = new WebClient();
var data = c.DownloadString("https://btc-e.com/api/2/btc_usd/ticker");
//Console.WriteLine(data);
JObject o = JObject.Parse(data);
maskedTextBox11.Text = o["high"];

But it's giving the error in the title.

like image 629
Katazui Avatar asked Feb 09 '14 15:02

Katazui


People also ask

Can we convert JToken to JObject C#?

How can I Convert a JToken To JObject? JObject is a subclass of JToken , so if payload is in fact a JObject , you can just cast it.

What is JToken in C#?

JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...

What is JArray C#?

JArray(Object) Initializes a new instance of the JArray class with the specified content. JArray(Object[]) Initializes a new instance of the JArray class with the specified content. JArray(JArray)


1 Answers

You are just required to add o["high"].ToString(); instead of o["high"]; since JObject[] returns a JToken and you are trying to assign maskedTextBox11.Text, which is a string, with it.

If you want the ToString() of the object represented by the token you can do it as the following:

MyType obj = o["high"].ToObject<MyType>();
string s = obj.ToString();
like image 113
Tamir Vered Avatar answered Sep 28 '22 00:09

Tamir Vered