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.
Related
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 can i parse a json string in c# controller
public ActionResult GetAjaxSession(string search)
{
...
}
Variable which containt the json string :
search
The Json string :
[{"id_employe":"35"},{"id_employe":"80"},{"id_employe":"136"},{"id_employe":"140"}]
I want to get all id_employe from the string
But parsing would be the right way, to get the right data out of your string.
Example with using Newtonsoft.Json:
var objects = JsonConvert.DeserializeObject<List<MyObj>>(jsonText);
With the class:
public class MyObj
{
public string id_employe { get; set; }
}
Malior's approach is perfectly fine, it's a typed approach. I'd like to mention an alternative way, using Linq and dynamic:
var jsonText="[{\"id_employe\":\"35\"},{\"id_employe\":\"80\"},"
+"{\"id_employe\":\"136\"},{\"id_employe\":\"140\"}]";
var objects = JsonConvert.DeserializeObject<List<dynamic>>(jsonText);
var values = objects.Select(s=>s.id_employe).ToList();
Fiddle
This will create a list, so values contains the following elements:
35,80,136,140
Because it is dynamic, you don't need to declare an extra class. Note that both approaches will throw a JsonReaderException if there is anything wrong with the JSON string (e.g. missing [ etc.). And if the property name isn't found it can throw a RuntimeBinderException - so you should use a try ... catch block.
I am trying to create a json formatted string using c# in UWP without JSON.Net, but I am just not understanding how to get there. Let's say I wanted to create the following json dynamically:
[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]
From everything I have read, it would seem that I need a class that defines the content of my json. For example:
class accountTypes
{
public int id { get; set; }
public string type { get; set; }
}
From there, it would seem that I only need to create a list of type "accountTypes" and then add each "id" to the list.
List<accountTypes> jsonList = new List<accountTypes>();
int numOfChildren = AccountTypesList.Children.Count;
for (int i = 0; i < numOfChildren; i++)
{
if (((CheckBox)AccountTypesList.Children[i]).IsChecked == true)
{
jsonList.Add(new accountTypes() { id = (int)(double)((CheckBox)AccountTypesList.Children[i]).Tag });
}
}
While I am 99% sure that the above code is very flawed, it does not crash on me, so that is a start at least. What I am struggling with now though is how I would serialize the list "jsonList". Everything I have read thus far either points to JSON.net or the JavaScriptSerializer Class, and not Windows.Data.Json. If I could see a simple example on how to serialize json using Windows.Data.Json, then I could at least visualize what is going on with my list and could correct it accordingly. That being said, how do I serialize an array or a list using Windows.Data.Json?
First of all, there's no built-in JSON-serializer that handles all the mapping for you. This is exactly what JSON.NET is doing for you. Therefore, you have to take the manual and long way.
To create exactly this result:
[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]
You have to use the JsonArray class. For example, pass your jsonList object to a method like this:
public string ToJson(List<accountTypes> objectList)
{
var jArray = new JsonArray();
foreach (var at in objectList)
{
jArray.Add(ToJson(at));
}
return jArray.ToString();
}
Whereas you use this method to create a JsonObject for your class object itself (as manual step as well):
public JsonObject ToJson(accountTypes at)
{
var jObj = new JsonObject();
jObj.SetNamedValue("id", JsonValue.CreateNumberValue(at.id));
return jObj;
}
I'm facing a wierd problem when converting Json Unicode(?) to UTF8
"V\u00E4xj\u00F6" should be "Växjö"
Right now it seems like I've tried everything possible, but no luck.
Any coding ninjas out there that may sit on a solution? I'm sure it's fairly easy but still can't seem to figure it out.
Thank you
As Tomalak pointed out, it can be done using the System.Web.Helpers.Json.Decode method (no external libraries, .NET Framework). You need to build a simple JSON object to fetch the decoded text:
// helper class
public class Dummy
{
public String Field { get; set; }
}
//
var value = "V\u00E4xj\u00F6";
var sb = new StringBuilder();
sb.Append("{");
sb.Append(String.Format(#"""Field"" : ""{0}""", value));
sb.Append("}");
var dummy = Json.Decode(sb.ToString());
Console.WriteLine(dummy.Field);
// it works also without helper class
var obj = Json.Decode(sb.ToString());
Console.WriteLine(obj.Field);
The output is:
Växjö
Växjö
One possibility would be to use the Json.NET library to decode the string (or maybe for the whole JSON handling?). The deserializer decodes the string automatically. My test code looks like this:
// placeholder for the example
public class Sample
{
public String Name { get; set; }
}
//
var i = #"{ ""Name"" : ""V\u00E4xj\u00F6"" }";
var jsonConverter = Newtonsoft.Json.JsonConvert.DeserializeObject(i);
Console.WriteLine(jsonConverter.ToString());
//
var sample = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(i);
Console.WriteLine(sample.Name);
The output is:
{
"Name": "Växjö"
}
Växjö
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);