so I have a JSON text and I need to Extract Value of some fields from it
{"data":{"shortcode":{"id":"id123","shortcode":"alpha1","by":{"page_info":{"has_next_page":true,"cursor":"sometext=="},"edges":[{"node":{"id":"id1234","username":"admin123","full_name":"admin name",}},{"node":{"id":"id4321","username":"user123","full_name":"user ",}}]}}},"status":"ok"}
now I need the value of every single "username" field and "cursor" from it
I'm new to this topic and I appreciate any kind of help
You could install Newtonsoft.Json, as a Nuget package, if you don't already have it installed in your project. Then use JsonConvert.DeserializeObject() method to parse it into a dynamic object type, using which you can access all its fields/properties.
Code would look something like this-
Add referenceto Newtonsoft.Json
using Newtonsoft.Json;
DeserializeObject method to parse a string into dynamic type (dynamic can be used instead of var)
var obj = JsonConvert.DeserializeObject<dynamic>(text);
For cursor field mentioned in your example
Console.WriteLine(obj.data.shortcode.by.page_info.cursor);
Iterate for each username mentioned your example
foreach (var edge in obj.data.shortcode.by.edges)
{
Console.WriteLine(edge.node.id);
}
NOTE- Because you are using a dynamic type, you will have to be sure that you check for null values to avoid any "NullRefereneException".
Well you can make a new class that match the structure of your json then deserialize the json into that class.
Related
I am using System.Text.Json package to use the serialization and deserialization.
I can deserialize a json string into an object when the type is explicitly specified like below.
var data = JsonSerializer.Deserialize<PersonType>(jsonString);
But the dynamic type does not work. Is it possible to deserialize without having to specify the type? Thank you!
var data = JsonSerializer.Deserialize<dynamic>(jsonString);
tl:dr JsonNode is the recommended way but dynamic typing with deserializing to ExpandoObject works and I am not sure why.
It is not possible to deserialize to dynamic in the way you want to. JsonSerializer.Deserialize<T>() casts the result of parsing to T. Casting something to dynamic is similar to casting to object
Type dynamic behaves like type object in most circumstances. In particular, any non-null expression can be converted to the dynamic type. The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time
docs.
The following code snippet shows this happening with your example.
var jsonString = "{\"foo\": \"bar\"}";
dynamic data = JsonSerializer.Deserialize<dynamic>(jsonString);
Console.WriteLine(data.GetType());
Outputs: System.Text.Json.JsonElement
The recommended approach is to use the new JsonNode which has easy methods for getting values. It works like this:
JsonNode data2 = JsonSerializer.Deserialize<JsonNode>(jsonString);
Console.WriteLine(data2["foo"].GetValue<string>());
And finally trying out this worked for me and gives you want you want but I am struggling to find documentation on why it works because according to this issue it should not be supported but this works for me. My System.Text.Json package is version 4.7.2
dynamic data = JsonSerializer.Deserialize<ExpandoObject>(jsonString);
Console.WriteLine(data.GetType());
Console.WriteLine(data.foo);
I have tried using System.Text.Json in a dynamic way and it just does not work in an easy and meaningful way it seems. So while not a direct answer to your question, but I was "forced" to use the good old Newtonsoft.Json that just works:
dynamic result = JObject.Parse(message);
I am using C# and trying to generate a JSON string from a dynamic object.
dynamic reply = new System.Dynamic.ExpandoObject();
reply.name = "John";
reply.wins = 42;
string json = System.Web.Helpers.Json.Encode(reply);
System.Console.WriteLine(json);
(Note, the above requires a reference to the System.Web.Helpers assembly.)
I was hoping for this to output the string:
{"name":"John","wins":42}
But it actually outputs:
[{"Key":"name","Value":"John"},{"Key":"wins","Value":42}]
What do I need to change to get the output I was hoping for?
Just download the Newtonsoft.Json Nuget package.
That's the preferred way of working with json in c#.
Your code using Newtonsoft would be:
dynamic reply = new System.Dynamic.ExpandoObject();
reply.name = "John";
reply.wins = 42;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(reply);
System.Console.WriteLine(json);
EDIT:
I just want to explain better why you're getting that result when you're using the System.Web.Helpers.Json.Encode method.
An ExpandoObject is an object which fields are defined at runtime, different than a regular object which fields/properties/methods .. are defined at compile-time. To be able to define them at run-time the expando object internally holds a dictionary, which is a collection of key-value pairs.
I don't know how that helper works but it's probably just a simple serializer and that's why it's serializing to an array of key- value pairs instead of the actual object you're expecting. The library Newtonsoft.Json is almost an standard for c# projects and obviously is aware of how the Expando Object works internally.
Using the Newtonsoft.Json tools:
using Newtonsoft.Json;
/// skip a bunch of other implementation details.
var json = Newtonsoft.Json.JsonConvert.SerializeObject(reply);
That's how I do it.
I have a json like this
{"1":"#ff0051","2":"#d000ff","3":"#2200ff","4":"#00ff59"}
How can I read these values since they don't have a property name? It is a bit difficult to think of a way.
Use JSON.Net
var s = "{\"1\":\"#ff0051\",\"2\":\"#d000ff\",\"3\":\"#2200ff\",\"4\":\"#00ff59\"}";
var o = JObject.Parse(s);
Then you can read the property value
Console.WriteLine(o["1"]);
Please note that you also need to install Json.NET Nuget Package.
I am working on a project that communicates a lot of data with a server. This data is in a json format. We end up creating a lot of dummy objects to parse the json data. This leads to having a lot of classes that just contain class members. Is there a better way of doing things?
thanks
Assuming that you are using NewtonSoft's JSON parser or something similar, you have a couple of choices here. The usual use case here is to deserialize to a named type, thus:
var parsedMessage = JsonConvert.DeserializeObject<Message>(content.AsString());
If you have many types for each differnet JSON message type you wish to receive and wish to avoid to, you can do the following:
var parsedMessage = JsonConvert.DeserializeObject<dynamic>(content.AsString());
This will give you a dynamic object that you can inspect and should also work given other Json libraries. Alternatively, NetwtonSoft also provides the following method:
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject);
This will allow you to deserialize to an anonymously typed object rather than a dynamic object.
I have a JSON String returned by my SOAP web service in .NET. It is as follows:
{
"checkrecord":
[
{
"rollno":"abc2",
"percentage":40,
"attended":12,
"missed":34
}
],
"Table1":[]
}
Now I want to parse this string to a JSON Object. I also read this where they have used this line of code:
JObject jsonObj = JObject.Parse(json);
So can I do the same by replacing "json" with my string name. Also do I need to reference any other dll except the NewtonSoft.dll ?
BTW, Here is the full webservice code
use new JavaScriptSerializer().Deserialize<object>(jsonString)
You need System.Web.Extensions dll and import the following namespace.
Namespace: System.Web.Script.Serialization
for more info MSDN
I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.
As #Maloric mentioned in his answer to this question:
var jo = JObject.Parse(myJsonString);
To use JObject, you need the following in your class file
using Newtonsoft.Json.Linq;
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.
And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);
[Serializable]
public class MyClass
{
public string myVar {get; set;}
etc.
}