This question already has answers here:
Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class
(9 answers)
Json.NET JsonConvert.DeserializeObject()
(1 answer)
Closed last month.
I need the usernames and their points from the response.
This is what the body looks like:
{
"_total": 3,
"users": [
{
"username": "person1",
"points": 3
},
{
"username": "person2",
"points": 2
},
{
"username": "person3",
"points": 1
}
]
}
My Code:
List<string> data;
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<List<string>>(body);
foreach (var i in data) {
Debug.Log(i);
}
}
I would like to save the body to the List data and get the usernames and their points from there.
You can create a custom class to hold the data from the JSON response, like so:
class UserData
{
public string username { get; set; }
public int points { get; set; }
}
Then, you can change your deserialization code to use this class instead of a List of strings:
List<UserData> data;
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<List<UserData>>(body);
foreach (var i in data) {
Debug.Log(i.username + ": " + i.points);
}
}
This should allow you to access the username and points from the JSON response using the "data" variable.
Related
I am pretty new to JSON and C# and have created an Azure Function that ties back to Snowflake which requires a very specific type of JSON response. I would like assistance if any in turning a JSON response I'm getting to a slightly different formatted response.
{
"access_token": "access token value here" , "user": "user_val"
}
to looking like
{
"data":
[
[ 0, { "access_token" : "access token value here", "user" : "user_val" } ]
]
}
I need create a nested array with "data" as the parent and a row number response starting at 0.
Using Json.NET:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string json = #"{
""access_token"": ""access token value here"" , ""user"": ""user_val""
}";
Access a = JsonConvert.DeserializeObject<Access>(json);
var accessCollection = new AccessCollection
{
Data = new List<Access> { a }
};
json = JsonConvert.SerializeObject(accessCollection, Formatting.Indented);
Console.WriteLine(json);
}
}
public class Access
{
[JsonProperty("access_token")]
public string AccessToken
{
get;
set;
}
[JsonProperty("user")]
public string User
{
get;
set;
}
}
public class AccessCollection
{
[JsonProperty("data")]
public List<Access> Data
{
get;
set;
}
}
In addition, I consider the inner array is not usual because the data type are int and object. In general, they should be of same type. Because of that, I use a single dimensional array instead.
Please modify the codes according to situation.
.NET Fiddle
I have created a LUIS account and did everything that was needed.
I have written the following code and got the result from LUIS.
I need to know how to save the result of my query to a variable, using which I would like to search the database or web.
Below is the code..
static async void MakeRequest(string qz) {
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
var luisAppId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var endpointKey = "XXXXXXXXXXXX";
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", endpointKey);
// The "q" parameter contains the utterance to send to LUIS
queryString["q"] = qz;
// These optional request parameters are set to their default values
queryString["timezoneOffset"] = "0";
queryString["verbose"] = "false";
queryString["spellCheck"] = "false";
queryString["staging"] = "false";
var endpointUri = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" + luisAppId + "?" + queryString;
var response = await client.GetAsync(endpointUri.);
var strResponseContent = await response.Content.ReadAsStringAsync();
// Display the JSON result from LUIS
Console.WriteLine(strResponseContent.ToString());
}
And also here is the query result.
{
"query": "the best resturant in Paris",
"topScoringIntent": {
"intent": "city",
"score": 0.436210483
},
"entities": [
{
"entity": "paris",
"type": "city",
"startIndex": 22,
"endIndex": 26,
"score": 0.7153605
}
]
}
Now I want to save this
"entity": "paris",
"type": "city",
to a variable. Kindly guide me as I am completely new to MS LUIS.
example:
string result = "paris" /// which the value should be taken from luis query
string type = "city" /// which the value should be taken from luis query
One option is to reference Newtonsoft.Json NuGet package to your project.
Then you may create two classes (feel free to change the name)
public class LuisExtractionLuisResult
{
public List<LuisEntity> entities { get; set; }
}
public class LuisEntity
{
public string entity { get; set; }
public string type { get; set; }
}
Then one example of use is
var target = JsonConvert.DeserializeObject<LuisExtractionLuisResult>(strResponseContent);
requested values are then retrieved by:
string result = target.entities[0].entity;
string type = target.entities[0].type;
And one more question, if in the query we have more than one entities.
how to get that as well?
foreach(LuisEntity oneEntity in target.entities)
{
string result oneEntity.entity;
string type = oneEntity.type;
}
Can somebody help me to parse the json and get the details.
Lets say i have Top2 input parameter as Police and i want to know the respective Top3 and in that Top3 array i need to check whether Test1Child value is there or not.
I am using newtonsoft json + c# and so far i can get till DeviceTypes using below code
var json = File.ReadAllText(jsonFile); // below json is stored in file jsonFile
var jObject = JObject.Parse(json);
JArray MappingArray =(JArray)jObject["Top1"];
string strTop1 = ObjZone.Top1.ToString();
string strTop2 = ObjZone.Top2.ToString();
var JToken = MappingArray.Where(obj => obj["Top2"].Value<string>() == strTop2).ToList();
//Json
{
"Top1": [
{
"Top2": "Test1",
"Top3": [
"Test1Child"
]
},
{
"Top2": "Test2",
"Top3": [
"Test2Child"
]
}
]
}
I'd use http://json2csharp.com/ (or any other json to c# parser) and then use C# objects (it's just easier for me)
This would look like that for this case:
namespace jsonTests
{
public class DeviceTypeWithResponseTypeMapper
{
public string DeviceType { get; set; }
public List<string> ResponseTypes { get; set; }
}
public class RootObject
{
public List<DeviceTypeWithResponseTypeMapper> DeviceTypeWithResponseTypeMapper { get; set; }
}
}
and the use it like that in code:
var rootob = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(str);
var thoseThatHaveNotUsed = rootob.DeviceTypeWithResponseTypeMapper.Where(dtwrtm =>
dtwrtm.ResponseTypes.Any(rt => rt == "NotUsed"));
foreach (var one in thoseThatHaveNotUsed)
{
Console.WriteLine(one.DeviceType);
}
this code lists all the Device types that have "NotUsed" among the responses.
version 2 (extending your code) would look like that, i believe:
static void Main(string[] args)
{
var json = str; // below json is stored in file jsonFile
var jObject = JObject.Parse(json);
JArray ZoneMappingArray = (JArray)jObject["DeviceTypeWithResponseTypeMapper"];
string strDeviceType = "Police";
string strResponseType = "NotUsed";
var JToken = ZoneMappingArray.Where(obj => obj["DeviceType"].Value<string>() == strDeviceType).ToList();
var isrespTypeThere = JToken[0].Last().Values().Any(x => x.Value<string>() == strResponseType);
Console.WriteLine($"Does {strDeviceType} have response type with value {strResponseType}? {yesorno(isrespTypeThere)}");
}
private static object yesorno(bool isrespTypeThere)
{
if (isrespTypeThere)
{
return "yes!";
}
else
{
return "no :(";
}
}
result:
and if you'd like to list all devices that have response type equal to wanted you can use this code:
var allWithResponseType = ZoneMappingArray.Where(jt => jt.Last().Values().Any(x => x.Value<string>() == strResponseType));
foreach (var item in allWithResponseType)
{
Console.WriteLine(item["DeviceType"].Value<string>());
}
I got a response from a webservice as shown below
{
"header": {
"sourceId": "1002",
"mndAction": "CREATE",
"msgId": "msg10022",
"errMsg": null,
"txnStatusFlg": "1",
"successMsg": "SUCCESS"
},
"response": {"responseString": "Required Data"}
}
I want to get the value of responseString from the above json data.
For the response
{"Status":"success","DocRepoId":225,"Details":"success",
"ErrorCode":"","responseString": "Required Data"}
I used the code
var deserializer = new JavaScriptSerializer();
var someObject = deserializer.Deserialize<Dictionary<string, string>>
(response);
string responseString= someObject["responseString"].ToString();
to get the value of responseString but in this case its showing error.
I'm looking for a solution without using json.net or anything similar.
My project is on .net version 3.5.
Here it goes an example of what i told you in comment.
Using this classes:
class Test
{
public Response Response { get; set; }
}
class Response
{
public string ResponseString { get; set; }
}
You can get what you want with this code:
JavaScriptSerializer s = new JavaScriptSerializer();
string json = #"{
""header"": {
""sourceId"": ""1002"",
""mndAction"": ""CREATE"",
""msgId"": ""msg10022"",
""errMsg"": null,
""txnStatusFlg"": ""1"",
""successMsg"": ""SUCCESS""
},
""response"": { ""responseString"": ""Required Data""}
}";
Test t = s.Deserialize<Test>(json);
var responseString = t.Response.ResponseString;
I want to convert this JSON return from php file into c#. But as a newbie don't know how, please help.
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
The above JSON is returned from my PHP file.
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
List<Response> json ;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
The Classes I am using are:
public class Response
{
public string user_id { get; set; }
public string crtloc_lat { get; set; }
public string crtloc_lng { get; set; }
}
public class RootObject
{
public List<Response> response { get; set; }
}
I am getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[afterall.Response]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
The following line is wrong based on your sample JSON.
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
Try changing it to:
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
Edit:
WebRequest request = WebRequest.Create("http://localhost/abh/returntest.php");
WebResponse response = await request.GetResponseAsync();
RootObject json;
using (var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
foreach (var item in json)
{
Console.WriteLine("id={0},latitude={1},longitude={2}",item.user_id,item.crtloc_lat,item.crtloc_lng);
}
rewrite the following line :
json = JsonConvert.DeserializeObject<List<Response>>(stream.ReadToEnd());
as
json = JsonConvert.DeserializeObject<Response>(stream.ReadToEnd());
From your testlink in the comment of your post. Your response is not:
{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"}
]}
as you post but rather:
connected{"response": [
{"user_id":"26","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"},
{"user_id":"27","crtloc_lat":"9.350192","crtloc_lng":"-95.391006"},
{"user_id":"28","crtloc_lat":"47.678238","crtloc_lng":"-122.131416"
}]
}
This is not corresponding to your sample code. Remove the
connected{ }
wrapping or return correct json for a connected object (whatever the connect is). If you remove the wrapping it should work as #Dietz posted.