C# How to know which element is root object for deserialization? - c#

I used json2csharp to get this:
http://pastebin.com/pbDYCrWk
From that, I wish to get the title that is held in the Oembed section.
I'm using this code:
string url = "http://www.reddit.com/r/all.json";
string jsonText = await DoStuff(url);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonText);
var deserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Page.Oembed>(json);
string test = deserializeObject.title;
And I assumed it would work, however on the line with the deserializeObject variable, I get an error saying it can't do it.
I tried using Page.RootObject however it doesn't work either, and I assumed it would since it seems to be the root.
What am I doing wrong and how can I solve it? Thanks.

If you used Json2CSharp then it is RootObject:
public class RootObject
{
public string kind { get; set; }
public Data data { get; set; }
}
Should be:
var deserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<JuicyReddit.RootObject>(json);

Related

extracting a value from a JSON string

I'm working on a Blazor application and I have a Json string from which I'm trying to extract a value.
Json Data looks like this:
{"a1":"a1234","e1":"e1234}
I'm trying to extract the a1 value from this which is "a1234"
My JSON Data is in a string variable, rawJsonData. I'm trying to use the JsonSerializer.Deserialize, but I'm not sure how to completely use it...
#code
{
string rawJsonData = JsonData (this is not the actual data, it's being pulled from elsewhere)
var x = System.Text.Json.JsonSerializer.Deserialize<???>(rawJsonData)
}
is this the right way to approach this? I'm not sure what to put in place of ??? above. Anyone has experience with this.
If you use Newtonsoft, as suggested in another answer, you don't even have to create a class.
JObject temp = JObject.Parse(rawJsonData);
var a1 = temp["a1"];
Create a class:
public class Root
{
public string a1 { get; set; }
public string e1 { get; set; }
}
Then Deserialize it into that class:
var x = System.Text.JsonSerializer.Deserialize<Root>(rawJsonData);
Or use Newtonsoft.Json:
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(rawJsonData);
To retrieve the value of a1 just call: x.a1
If you want to stick with System.Text.Json and don't want to create a class/struct for the data (why not?), as suggested in comments, you can
var jsonData = "{\"a1\":\"a1234\",\"e1\":\"e1234\"}";
var doc = JsonDocument.Parse(jsonData);
var a1 = doc?.RootElement.GetProperty("a1").GetString();
Of course, a try catch around the conversion would help.

How can I add json data to a label in C#? ( windows forms )

so i want to get bitcoin price from a URL and see it in a label in my form.
URL
i tried to make a class for it with the code
public string price { get; set; }
but i don't know what to do after that, i searched a lot in google but they all show the result in list and etc
To deserialize, first you need to make a class with the attributes the JSON has. This page will help you a lot in that.
Once you have a class, you need to deserialize your JSON into that class. In C# I like to use JsonConvert from the library Newtonsoft.Json, you need to import it.
The method that deserializes it is JsonConvert.DeserializeObject.
One little example, let's say your class is called Bitcoin, then you would have to do it that way :
var myBitcoin = JsonConvert.DeserializeObject<Bitcoin>(yourJson);
EDIT: To pull your json from an URL you can use Webclient DownloadString method.
var myjson = new WebClient().DownloadString("url");
This post may also help you.
This should be your class.
public class APIResponse
{
public string symbol { get; set; }
public string price { get; set; }
}
Then in your function add these lines.
APIResponse response = new APIResponse();
response = JsonConvert.DeserializeObject<APIResponse>();
myPriceLabel.Text = response.price;
What did we do? We created a C# model same as the Json Data model and we took JSON data and converted it to APIResponse type so we can access it and use it as we like.
It can be achieved simply by converting the Json with generic object
var myBitcoin = JsonConvert.DeserializeObject<object>(yourJson);
thank you all for answering but i found the solution!
the code should be like this
string url = "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT";
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString(url);
JavaScriptSerializer oJS = new JavaScriptSerializer();
PriceClass obj = new PriceClass();
obj = oJS.Deserialize<PriceClass>(json);
BTCPrice_Label.Text = obj.price;
}
and the class should be like this
using System;
public class PriceClass
{
public string symbol { get; set; }
public string price { get; set; }
}

How to convert a JSON string to PSObject?

I want to write a PowerShell function in C#. During the process I receive a string with JSON content.
My sample json content is:
string json = "{'TestNr':{'Name':'CSHARP', 'Description':'Test Descriptiopn'}}"
This string should be converted to a PSObject just like ConvertFrom-Json would do.
I was trying to create an object with below lines. It works but it would require a lot of manual scripting especially if the JSON string becomes longer.
PSObject obj = new PSObject();
obj.Properties.Add(new PSNoteProperty("Head", "Children"));
I tried also the below line:
obj = (PSObject)TypeDescriptor.GetConverter(typeof(PSObject)).ConvertFromString(json);
For this I get however the error (I run the function in PowerShell 7):
TypeConverter cannot convert from System.String.
There are two ways you can parse the string in C# that would be the easiest to go with.
public class MyClass
{
public TestNRClass TestNR { get; set; }
}
public class TestNRClass
{
public string Name { get; set; }
public string Description { get; set; }
}
// In the main,
string json = #"{""TestNr"":{""Name"":""CSHARP"", ""Description"":""Test Descriptiopn""}}";
MyClass jobj = JsonConvert.DeserializeObject<MyClass>(json);
Console.WriteLine(jobj.TestNR.Name);
This is with the strong typed class object. This is what you should be using in C#.
Other way is to get an object
string json = #"{""TestNr"":{""Name"":""CSHARP"", ""Description"":""Test Descriptiopn""}}";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj.ToString());
Console.WriteLine(obj["TestNr"]["Name"].ToString());
// You can also add more keyValuePair
obj["NewVariable"] = "stest";
Console.WriteLine(obj.ToString()); // Shows the new item as well.

Strange JSON Deserialization c#

I'm having troubles with some Deserialization because I'm not receiving an object like I'm used to but an array. Lets to the code, how I've being doing it:
JSON received:
[{"gcm_regID":"fsdf2156fw62f1wfwe512g"}]
Deserialization
var result = JsonConvert.DeserializeObject<Gcm>(response);
Handlers Tried:
public class Gcm
{
public List<Gcm_reg> gcm_regID { get; set; }
}
public class Gcm_reg
{
public string gcm_regID { get; set; }
}
I've tried just the Gcm_reg as well and nothing seems to work. How can I deserialize this? By the way, I'm using the newsoft JSON.
Best regards,
IEnumerable<Gcm_reg> result = JsonConvert.DeserializeObject<IEnumerable<Gcm_reg>>(response);
You can deserialize the object as an array or IEnumerable
Object should be like
public class Gcm
{
public string gcm_regID { get; set; }
}
So Try it
var result = JsonConvert.DeserializeObject<IEnumerable<Gcm>>(response);
You can directly generate classes from Json by using link
To create same type of object
var outputList = new List<Gcm>();
//loop through this part based on number of input
var itemToAdd = new Gcm();
itemToAdd .regID = 'something';
outputList.Add(itemToAdd );
and send outputList to server.

Parsing JSON data with javascriptserializer throws exception

I am getting JSON data in following format:
"[[\"NAME\",\"state\"],\n[\"Alabama\",\"01\"],\n[\"Alaska\",\"02\"]]"
I am trying to parse it with System.Web.Script.Serialization.JavaScriptSerializer the following way:
[Serializable]
private class State
{
private string Name { get; set; }
private string Code { get; set; }
}
private static List<State> getStates(string jsonData)
{
var json = new JavaScriptSerializer();
var parsedResult = json.Deserialize<List<State>>(jsonData);
return parsedResult;
}
The error I am getting is Type 'State' is not supported for deserialization of an array.
What am I doing wrong?Please suggest a way out.
Update
I have somewhat solved the problem since I need only a collection of the data in a queryable format. The following code did the trick:
var parsedResult = json.Deserialize<List<string[]>>(jsonData);
You have found workaround, nevertheless I think it's good to have explanation for the issue.
The problem you have is in brackets; [] means array, whereas object is market with {}. This means that to deserialize input string in array of State objects your input string should be formatted in following way:
[{\"NAME\",\"state\"},\n{\"Alabama\",\"01\"},\n{\"Alaska\",\"02\"}]

Categories

Resources