Using a JSON array received as a string - c#

I'm receiving a string, output, that looks like this:
{family_name:XXX, given_name:XXX, locale:en, name:XXX, picture:XXX, profile:XXX, sub:XXX}
I'd like to get some of these values and store them in variables, but since it's a string I cant use indexing (I would've just used var x = output[0] etc)
How would I get a hold of these values?
Thanks in advance

The structure of the string is a JSON-object. Therefore, you must handle it as a JSON-object.
First parse it to JSON. eg. like this:
JObject json = JObject.Parse(YOUR_STRING);
And now to get the given value you wish, for instance family_name you can say:
string name = (string) json["family_name"];

I would recomend Json.Net.
Parse your string to json, and create a model that can hold those JSON values as
public class Person
{
public string family_name {get;set}
public string given_name {get;set;}
public List<string> siblings{get;set;}
}
(This could be done with https://quicktype.io/csharp/ or manually)
Then:
string json = #"{
'family_name': 'Foo',
'given_name': 'Bar',
'siblings': [
'Jhon',
'Doe'
]
}";
Person person = JsonConvert.Deserialize<Person>(json);
string familyName = person.family_name;
//Foo

Related

How can I serialize this Json using my model class?

I have having a problem how to get the empty list and define the properties and set the values in a static method.
FYI : I am also using the same properties id and parentID in another payload that is not a List..
//Here is the json I have
[
{
"id": 1,
"parentId": 4
}
]
//Here is my model class, my static method "Payload" and the properties of Json
public class Model
{
public int id { get; set; }
public int parentId { get; set; }
public static Model Payload()
{
return new Model
{
//How to get define the List here and set the values
}
}
}
The json you have is a List so, with Newtonsoft.Json, you can deserialize to a list.
var myModels = JsonConvert.DeserializeObject<List<Model>>(jsonString);
If the json string is empty "[]", it will create an empty list (not sure if that's what you were asking about the empty list of Model).
To convert the list to string:
var stringPayload = JsonConvert.SerializeObject(myModels);
What is your goal exactly ? You just want to load a model from a JSON string ? If not, what is this list exactly ? I think you should look at this : https://www.newtonsoft.com/json
It's a very popular library for manipulate JSON and data model related to it.

How to convert a string (json with scape chars) to dynamic object?

Good day everyone, I'm trying to convert a string that looks like this:
"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"
If I do a quick inspection when the code is running, it looks like this:
After applying the following line of code:
var Datos = JsonConvert.DeserializeObject<dynamic>(Resultado);
It returns the object with two curly braces
{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
How can I avoid those two curly braces after converting the string to dynamic object?
I need to use it like this at the end:
var foo = Datos.Token.Value;
Thank you very much for your help.
The effects you're seeing (escaped quotes in the string and the braces) are just how the debugger has chosen to display those values.
"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"
is actually a string that contains
{"Estado":true,"Token":"3D16C8D8-058C-4FA7-AEA2-1A764A083B72","Nombre":"Agente COV"}
and
{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
Is how the debugger has chosen to display the dynamic object with 3 properties with values
Estado - true
Token - "3D16C8D8-058C-4FA7-AEA2-1A764A083B72"
Nombre - "Agente COV"
The simplest way I'd tackle this would be to create a class for the JSON
public class MyObject{
public bool Estado { get; set; }
public Guid Token { get; set; }
public string Nombre { get; set; }
}
Then you can use Json.Net to deserialize it.
var json = "{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}";
var myObject = JsonConvert.DeserializeObject<MyObject>(json);
Then access the values like myObject.Token etc.
You can first parse your json with
dynamic Datos = JObject.Parse(yourjson);
and retrieve the value by
var foo = Datos.Token
Note - JObject is from newtonsoft

How to parse json string in c#

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.

Deserializing JSON into string array OR datatable in C#

string json = {"house":"#21-3-157/18, Sri Vaibhav","loc":"Subash nagar,Bolar","country":"India"}
getting error while deserialize mentioned json string in array
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List because the type requires a
JSON array (e.g. [1,2,3]) to deserialize correctly.
I've tried many different ways of doing this, each time failed. please help.
Use Json.NET.
Example from https://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm
string json = #"[
{
'Title': 'Json.NET is awesome!',
'Author': {
'Name': 'James Newton-King',
'Twitter': '#JamesNK',
'Picture': '/jamesnk.png'
},
'Date': '2013-01-23T19:30:00',
'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
}
]";
dynamic blogPosts = JArray.Parse(json);
dynamic blogPost = blogPosts[0];
string title = blogPost.Title;
Console.WriteLine(title);
// Json.NET is awesome!
string author = blogPost.Author.Name;
Console.WriteLine(author);
// James Newton-King
DateTime postDate = blogPost.Date;
Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.
Another example without dynamic https://www.newtonsoft.com/json/help/html/QueryJson.htm
You can use NewtonsoftJson library to parse json data easily without creating concrete class
using Newtonsoft.Json;
dynamic parse = Newtonsoft.Json.JsonConvert.DeserializeObject(json );
string house = parse.house.Value;
etc..
Your JSON string is not in a format to convert to JSON string array. If you want to Deserialize JSON string to List then your format should be like below,
string json = "[\"house\",\"loc\"]";
In you want your string to Desrialize to array then you need corresponding entity like below,
public class Address
{
public string House { get; set; }
public string Loc { get; set; }
public string Country { get; set; }
}
Then you should deserialize to that type,
string json = "[{\"house\":\"#21-3-157/18,Sri Vaibhav\",\"loc\":\"Subash nagar,Bolar\",\"country\":\"India\"}]";
List<Address> array = JsonConvert.DeserializeObject<List<Address>>(json);

Deserialize arbitrary JSON keys and raw values

Using JSON.Net I want to deserialize a JSON object that looks something like this:
"properties": {
"foo": 1,
"bar": "Fred",
"baz": [694481.61, 693638.0, 692624.65, 692354.54]
}
and end up with a dictionary<string,string> that looks like this:
{ "foo", "1" },
{ "bar", "\"Fred\"" },
{ "baz", "[694481.61, 693638.0, 692624.65, 692354.54]" }
The key points to note are:
The keys are not known in advance. (Hence the use of a dictionary rather than deserializing to a class with predefined properties foo, bar and baz.)
The value strings in the dictionary are the raw JSON text from the JSON stream. So strings include their encapsulating quotation marks, and arrays include their encapsulating square brackets.
What I have tried so far
Parse the values as JRaw objects. This would work if I knew the key names in advance: I could declare matching properties in my class as type JRaw - e.g. public JRaw foo { get; set; }. But the key names are not predefined so I can't.
Create a RawValueDictionaryConverter : JsonConverter custom converter that takes the stream and deserializes it directly to a dictionary<string,string>. I thought this would be straightforward, but the raw text of the original stream is not available inside ReadJson(); the stream has already been tokenized and ReadJson() only receives the interpreted token and token type.
Write my own tokenizer and forget about using Json.NET. It may come to this but I don't want to 'reinvent the wheel.'
You can deserialise to Dictionary<string, JRaw> which gets you half way there. For example:
//Example class
public class Root
{
public Dictionary<string, JRaw> properties { get; set; }
}
var json = "<from the question>";
var result = JsonConvert.DeserializeObject<Root>(json);
foreach (var property in result.Properties)
{
var value = property.Value.ToString();
}
If you still want the values as strings, you can convert like this:
var stringDictionary = result.Properties.ToDictionary(p => p.Key, p => p.ToString());

Categories

Resources