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.
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);
We have a string that is JSON {"value":1} that we need to convert to a Manatee.Json.JsonValue.
Using new JsonValue(value) returns "{\"value\":1}" but we are looking for an actual JSON value of {"value":1}.
We have toyed with JsonObject, and it is possible by converting our JSON to a dictionary, but it would be nice if there is an easier way.
I think you need JsonValue.Parse().
From there you can get a JsonObject from the .Object property. JsonObject is derived from Dictionary<string, JsonValue> so you should be able to do that conversation simply.
The documentation is linked on the GitHub readme at the top.
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.
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.
The serialization of the array returns the following JSON:
[{"Code":"AAAA","Description":"Description of AAAA"},{"Code":"BBBB","Description":"Description of BBBB"}]
My goal is to return the following JSON:
{"AAAA":{"Description":"Description of AAAA"},"BBBB":{"Description":"Description of BBBB"}}
You can achieve something simliar (not exactly the same you are expecting) if instead of serializing an array, build a temporary Dictionary and serialize it.
var dict = new Dictionary<String, YourClass>();
foreach (YourClass yourObj in listOfObjs)
{
dict[yourObj.Code] = yourObj;
}
// then serialize "dict"
You could add a rule to your JSON serializer to make it avoid serializing "code" property in YourClass, and you will end up with a JSON object exactly as you show in your example.
You'll need to either use a class that has the "AAAA" and "BBBB" properties, or you'll need to serialize a dictionary instead. As it is, you're serializing an array and getting an array.
The table on this blog post shows several search starting points.
.Net has built-in System.Web.Script.Serialization.JavaScriptSerializer, here, with examples
The .Net one doesn't specially serialize Dictionary the way you want, but some of the others do, I believe. However, I think there are reasons NOT to want a general serialization routine the way you've requested - though I can't list them certainly.