How to convert Json to Array c# - c#

I have been trying to convert Json response to C# Array and the thing is Json goes up from my head I dont understand its structure as its a mess for me.
here is the example response I have as Json
{
"status":"ok",
"urls":{
"phone":[
{
"url":"tel:+9230154XXXXX",
"uri":"+9230154XXXXX"
}
],
"sms":{
"url":"sms:+9230154XXXXX",
"uri":"+9230154XXXXX"
},
"vcf":"https:\/\/www.eac.com\/i2\/ajax\/item\/vcf\/"
},
"limitExceeded":false
}
Now all i want from this Json sms:+9230154XXXXX this value.
I am using Newtonsoft.Json in this example.
Bellow is what I have tried so far
JObject jObject = JObject.Parse(json);
JToken jphone = jObject["urls"];
number = (string)jphone["phone"]["sms"];

Usage:
jObject["urls"]["phone"].ToObject<PhoneEntry[]>()
Class:
public class PhoneEntry {
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
}

I never really worked with Newtonsoft.Json but the following should work for you:
JToken token = JToken.Parse(json);
string number = (string)token.SelectToken("urls.sms.url")

Related

How to get value from JSON objects in C#?

I've tried to get the values from the JSON object that I made a request from Google APIs. My goal is to get the data from transcript.
This is the JSON file.
{
"results": [
{
"alternatives": [
{
"transcript": "how old are you",
"confidence": 0.66882694
}
]
}
]
}
And I've tried to get the output by using this. But it doesn't work.
var result = ["result"][0]["alternative"][0]["transcript"].ToString()
When I query the data, It doesn't show anything, just empty string.
Convert your JSON to a class
Json2CSharp and you get:
public class Alternative
{
public string transcript { get; set; }
public double confidence { get; set; }
}
public class Result
{
public List<Alternative> alternatives { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Store it somewhere in your code.
Use Newtonsoft.Json package
Install Newtonsoft.Json NUGet Package in your solution and import it in your code:
using Newtonsoft.Json;
Now you can deserialize your json as you prefer as long as you have it in a string variable.
var yourObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
You may access your transcript value using:
var transcript = yourObject.results[0].alternatives[0].transcript;
SOLUTION (without using external library like NewtonSoft.Json):
Add reference System.Web.Extensions.
use an assembly System.Web.Script.Serialization;
CODE:
var jsonString = "{\"results\": [ {\"alternatives\": [ {\"transcript\": \"how old are you\", \"confidence\": 0.66882694 } ] } ]}";
var jsonDeserialized = serializer.Deserialize<dynamic> (jsonString);
Console.WriteLine (jsonDeserialized["results"][0]["alternatives"][0]["transcript"]); // Prints "how old are you"
Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.
Here is an example on how to parse a JSON string into a dynamic object:
string source = "{\r\n \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\", \r\n \"first_name\": \"Jerard\", \r\n \"last_name\": \"Jones\", \r\n \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n \"username\": \"Jerard.Jones\", \r\n \"gender\": \"female\", \r\n \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
.
Console which data you want show
Usually if I knew what the structure of the JSON looks like I would use class to parse it.
But you could always parse the string to JSON object anytime.
using Newtonsoft.Json.Linq;
var json=JObject.Parse(YOUR_JSON_STRING)
var result = json["results"][0]["alternative"][0]["transcript"].ToString()
https://dotnetfiddle.net/KSDcIP
Also your keys that you are requesting doesn't match the keys in the JSON

How to bind JSON response from httpClient.PostAsJsonAsync

I can httpClient.PostAsJsonAsync(path, content) fine.
However, this post returns some JSON with details of the response, eg:
{"StatusCode":200,"AccessCode":"92BEEB285ZB47DA","InternalMessage":null}
I need to access the AccessCode.
How can I do this cleanly and efficiently? Can I create an object like this:
public class GIResponse
{
public string StatusCode { get; set; }
public string AccessCode { get; set; }
public string InternalMessage { get; set; }
}
And map it to the result?
Or how would I just traverse the JSON and pull out the AccessCode?
I have searched quite extensively but surprisingly I can't find anything on Google - perhaps as this is the result from a Post, not a Get.
How can I do this?
Provided that you get the responseText using httpResponse.Content.ReadAsStringAsync, you can use Json.NET's JObject and define it as dynamic:
dynamic j = JObject.Parse(#"{""StatusCode"":200,""AccessCode"":""92BEEB285ZB47DA"",""InternalMessage"":null}");
Console.WriteLine(j.AccessCode);
Also you can use JsonConvert:
var result = JsonConvert.Deserialize<MyModel>(resposeText);
Obviously, if you already have a model, you do not read it as a string and you can simply read it as your model:
var result = httpResponse.Content.ReadAsAsync<MyModel>();

How do I deserialize this JSON array (C#)

I am struggling with a subject that has a lot of variants, but I can't seem to find one that works for me, and I think it's because of the way that my JSON array is.
I'm not an expert in C# or JSON, but I already manage to "almost" get this to work. I need to get hand with the class that the JSON will deserialize to.
When I run the code I dont get an error, just a nulls in the xKisokData var.
The JSON data that I am getting. Their are these two different ones.
"{\"Event\": \"sConnection\",\"data[device]\": \"fb16f550-2ef1-11e5-afe9-ff37129acbf4\",\"data[mode]\": \"customer\",\"data[starttime]\": \"2015-07-22T16:07:42.030Z\",\"data[endtime]\": \"\"}"
"{\"Event\": \"Log\",\"data[id]\": \"2015-07-22T16:07:23.063Z\",\"data[messages][0][source]\": \"server\",\"data[messages][0][message]\": \"Server is listening on port 1553\"}"
The code I have so far:
// Read in our Stream into a string...
StreamReader reader = new StreamReader(JSONdataStream);
string JSONdata = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
wsKisokData[] xKisokData = jss.Deserialize<wsKisokData[]>(JSONdata);
My Class:
namespace JSONWebService
{
[DataContract]
[Serializable]
public class KisokEvent
{
public string eventTrigger { get; set; }
}
[DataContract]
[Serializable]
public class KisokData
{
public string data { get; set; }
}
[DataContract]
[Serializable]
public class wsKisokData
{
public KisokEvent KDEvent { get; set; }
public List<KisokData> KDData { get; set; }
}
}
I am sure that I don't understand the Deserialize process. Thanks for the help.
EDIT:
I put the JSON in the top part right from the debugger, here is the strings.
{
"Event": "sConnection",
"data[device]": "fb16f550-2ef1-11e5-afe9-ff37129acbf4",
"data[mode]": "customer",
"data[starttime]": "2015-07-22T16:07:42.030Z",
"data[endtime]": ""
}
{
"Event": "Log",
"data[id]": "2015-07-22T16:07:23.063Z",
"data[messages][0][source]": "server",
"data[messages][0][message]": "Server is listening on port 1553"
}
I would HIGHLY recommend using the json.net package off nuget instead.
You can generate template classes (models) for it by pasting the json into http://json2csharp.com/
Then use said models to convert the json into a c# object (deserializing) by doing a
var jsonStructure = JsonConvert.DeserializeObject<model>(json)
And query as if it was just a standard object
foreach (var x in jsonStructure.KDData)
{
doAction(x.data);
}
// for example

RestSharp: Converting results

I get the following JSON that I am trying to convert to a business object using RestSharp
{
"valid":true,
"data":[
{
"dealerId":"4373",
"branchId":"4373",
}
]
}
I wish to convert to:
public class Dealer
{
public string dealerId ;
public string branchId;
}
But this fails, though the JSON is fine:
var client = new RestClient("http://www.????.com.au");
var request = new RestRequest(string.Format("service/autocomplete/dealer/{0}/{1}.json", suburb.PostCode, suburb.City.Trim().Replace(" ", "%20")), Method.GET);
var response2 = client.Execute<Dealer>(request);
return response2.Data;
Your business object doesn't match the response JSON you are getting back. If you want your response to serialize, your C# object would look something like
public class DealerResponse
{
public bool valid { get;set; }
List<Dealer> data { get;set; }
}
public class Dealer
{
public string dealerId;
public string branchId;
}
I haven't tested this code, but even though you are only interested in the information in 'data', your response C# objects still need to represent the whole JSON response to serialize correctly.
Hope that helps.

Convert json to a C# array?

Does anyone know how to convert a string which contains json into a C# array. I have this which reads the text/json from a webBrowser and stores it into a string.
string docText = webBrowser1.Document.Body.InnerText;
Just need to somehow change that json string into an array. Been looking at Json.NET but I'm not sure if that's what I need, as I don't want to change an array into json; but the other way around. Thanks for the help!
just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:
string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";
You'd need to create a C# class called, for example, Person defined as so:
public class Person
{
public int Age {get;set;}
public string Name {get;set;}
}
You can now deserialize the JSON string into an array of Person by doing:
JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons = js.Deserialize<Person[]>(json);
Here's a link to JavaScriptSerializer documentation.
Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.
using Newtonsoft.Json;
Install this class in package console
This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.
Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere
This is my class:
public class ToDoItem
{
public string text { get; set; }
public string complete { get; set; }
public string delete { get; set; }
public string username { get; set; }
public string user_password { get; set; }
public string eventID { get; set; }
}
In HttpContent section where you requesting data by GET request
for example:
HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.
See their examples:
string myJsonString = #"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by #Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
One Situation that wasn't covered in the other responses is when you don't know the type of what the JSON object contains. That was my case as I needed to be able to NOT type it and leave it dynamic.
var objectWithFields = js.Deserialize<dynamic[]>(json);
Note: it is definitely preferred to have a type, in some cases, it is not possible, that's why I added this answer.

Categories