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
Related
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'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
I'm trying to parse to a C# object a string containing a JSON that looks like that :
I know it's not really valid json but I can't choose it, it's sent by a device. That's why I've tried to replace the [] by {} to make it look like a valid object.
[2, "2", "text", {Object}]
I've created the following class:
public class MyClass
{
[JsonProperty(Order = 0)]
public int TypeRequest { get; set; }
[JsonProperty(Order = 1)]
public string UniqueID { get; set; }
[JsonProperty(Order = 2)]
public string Action { get; set; }
[JsonProperty(Order = 3)]
public JObject Payload { get; set; }
}
I want to parse the {Object} later (I need to know the "Action" property first because the object depends on the action).
So far I've done :
string userMessage = "[2, "2", "text", {Object}]";
if (userMessage.Length > 2)
{
// We need to remove the first [ and the last ] to be able to parse into a json object
StringBuilder sb = new StringBuilder(userMessage);
sb[0] = '{';
sb[sb.Length - 1] = '}';
userMessage = sb.ToString();
}
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyClass objectJSON = jsonSerializer.Deserialize<MyClass >(userMessage);
But it doesn't work I get the following exception:
Invalid object passed in, ':' or '}' expected. (3): {Object}}
I've also tried with JObject.Parse instead and I got:
Invalid JavaScript property identifier character: ,. Path '', line 1,
position 2.
Do you know how to do it? I would like to avoid having to split my JSON by commas and have the cleanest way to do it.
It's not really a valid JSON because of {Object} so I removed it. You can technically do json.Replace("{Object}", "something else") to make it easier. Because you deal with different types in array, it may not be a one step process. Here is an idea for you:
var json = "[2, \"2\", \"text\"]";
var array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
switch (item.Type)
{
case JTokenType.Integer:
// todo: your parsing code
break;
case JTokenType.String:
break;
// etc.
}
}
I used JSON.NET library to parse JSON. You can install it using nuget:
Install-Package Newtonsoft.Json
If you can, I'd recommend you to fix the JSON source to provide you with a valid JSON that can be parsed to an object without use of low-level classes like JToken, JArray, JObject etc.
I've got a JSON file that looks like this. It's basically a JSON file taken stright from Wikipedia using their API.
{
"batchcomplete": "",
"query": {
"pages": {
"31329803": {
"pageid": 31329803,
"ns": 0,
"title": "Wiki Title",
"extract": "<p><b>Your Wiki Title</b></p>"
}
}
}
}
The number generated under "pages" (which is the pageID) is random. I'm trying to retrieve the "extract" value, but I can't seem to get it.
I'm using Visual Studio & using NewtonSoft JSON.net for parsing. I've created a class for retrieving the data I want, and it looks like this.
public class WikiPage
{
public string title { get; set; }
public int pageid { get; set; }
public int ns { get; set; }
public string extract { get; set; }
}
I'm trying to bypass the JSON tree & get the value I want. The code I use to get the value are as follows:
static void Main(string[] args)
{
// Getting JSON string from file
string JSONString = File.ReadAllText("wiki.json");
JObject wikiSearchResult = JObject.Parse(JSONString);
IList<JToken> wikiPages = wikiSearchResult["query"]["pages"].Children().ToList();
JToken result = wikiPages[0];
var wp = JsonConvert.DeserializeObject<WikiPage>(result.ToString());
// Writing data
Console.WriteLine(wp.extract);
Console.ReadLine();
}
When I run the program program, I get an error:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.dll
Additional information: Error converting value "31329803" to type
'JSON_test.WikiPage'. Path '', line 1, position 10.
I've tried many things, but no luck. Maybe there is a simpler way to do it, but I'm pretty much stuck right now, can someone help me?
You're almost done, just get result this way:
JToken result = wikiPages[0].Children().First();
You can't deserialize a key value pair like that. Try this instead :
var json = JObject.Parse(JSONString);
var pages = json["query"]["pages"].ToObject<Dictionary<string, WikiPage>>();
var page = pages.First().Value;
Console.WriteLine(page.extract);
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\"}]