I have a Json and I want to get it in my c# object.
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_ = JsonConvert.DeserializeObject<object>(json);
Here, I get the Json in the format of:
{{
"pipeline" : {
"url" : "url1",
"idP" : 1
},
"id": 1234,
"name" : "test1",
"state" : "inprogress",
"date" : "date"
}}
Now, from this JSON, I just want the id and idP.
How can I do that? Should I create a class with all the properties?
Can I please get a sample code?
If you just want id and idP, you don't need to create the classes and deserialize json. You can just parse it
var jsonParsed = JObject.Parse(json);
var id = (Int32)jsonParsed["id"]; //1234
var idP = (Int32) jsonParsed["pipeline"]["idP"]; //1
but you have to fix your json, by removing extra pair {}. You can make it manually if it is a typo. But if it is a bug, you can use this code, before parsing
json=json.Substring(1,json.Length-2);
or for example you can create one class
public class Pipeline
{
public string url { get; set; }
public int idP { get; set; }
}
and deserialize only one part of json
Pipeline pipeline = jsonParsed["pipeline"].ToObject<Pipeline>();
Related
I have slightly annoying use case.
So, I am calling an API . The APi returns some json, which contains a json object with x amount of fields:
{
"status": "ok",
"result": {
"firstprovider": [ .... ],
"secondprovider": [ ...],
"thirdprovider": [ ... ]
}
}
In this example, only three provider are returned, but I could get more or less than that, and their names may vary. It's quite important that I save those names.
The "providers" inside of "result" are of the same type, so I can easily deserialize those to a certain model.
Now, I would normally expext "result" to be a json array of elements, so I could easily deserialize "result" into a List<LiveShopperEventModel>.
Currently, I made a hacky solution, creating a Dictionary<string,Provider> where the key is the name of the provider, and then I later use selectmany to flatten it into a list.
But, I was wondering if there exists some way in c#, that would allow me to convert the "result", into an array, which would make deserialization a lot simpler for me.
So, does anyone know of a way, or a resource that in c# can help in changing the types of json elements, and in this case, making a json object into a json array, with the fields becoming elements in the list?
Reproducing concept with minimal example
So, let's say my json looks like this:
{
"status": "ok",
"result": {
"firstprovider": [ {"name":"John"}, {"car":"BMW"}, {"surname":"Johnson"} ],
"secondprovider": [ {"name":"Zoe"}, {"car":"Ford"}, {"surname":"johnsøn"}],
"thirdprovider": [{"name":"Elliot"}, {"car":"Volkswagen"}, {"surname":"Jackson"} ]
}
}
Then I can deserialize it as in the following code snippet:
string json = "{\r\n\"status\": \"ok\", \r\n\"result\": { \r\n \"firstprovider\": [ {\"name\":\"John\"}, {\"car\":\"BMW\"}, {\"surname\":\"Johnson\", \"age\":30, \"car\":\"fast\"} ],\r\n \"secondprovider\": [ {\"name\":\"Zoe\"}, {\"car\":\"Ford\"}, {\"surname\":\"johnsøn\", \"age\":31, \"car\":null}], \r\n \"thirdprovider\": [{\"name\":\"Elliot\"}, {\"car\":\"Volkswagen\"}, {\"surname\":\"Jackson\", \"age\":32, \"car\":null} ] \r\n }\r\n }\r\n";
// deserializing to a dictionary
var resultDict = JsonConvert.DeserializeObject<ResultModel>(json);
// and now flattening the structure, so that it is a list of "ProviderModel"
// this is the part that feels hacky to me
var providerModelList = resultDict.result.SelectMany(listOfEvents => {
listOfEvents.Value.Select(Provider =>
{
Provider.provider = listOfEvents.Key;
return Provider;
}).ToList();
return listOfEvents.Value;
}).ToList();
public class ResultModel
{
[JsonProperty("result")]
public Dictionary<string, List<ProviderModel>> result { get; set; }
}
public class ProviderModel
{
public string provider { get; set; }
public string name { get; set; }
public string surname { get; set; }
}
The `selectmany" part feels hacky to me, since, i'm combining linq queries in a way that feels overly complicated
Instead, I think it would be much nicer, is the result class could just look like:
public class ResultModel
{
[JsonProperty("result")]
public List<ProviderModel> result { get; set; }
}
you can try something like this
List<ProviderModel> providerModelList = ((JObject)JObject.Parse(json)["result"])
.Properties()
.Select(x => GetValues(x))
.ToList();
public ProviderModel GetValues(JProperty jProp)
{
var providerModel = new JObject(((JArray)jProp.Value)
.Select(jo => ((JObject)jo).Properties().First()))
.ToObject<ProviderModel>();
providerModel.provider = jProp.Name;
return providerModel;
}
Im writing an API automation test with RestSharp.Any kind of help will be greatly appreciated!
I'm getting data values from the response & I need to write few values to my json file (which I will use for another test putting them as a body).
I managed to get 1 value from JArray but I need 2 more values and I cant wrap my head around how to do that.
Im attaching my api test code & the data I get from the response + the data I managed to write into my json file.
The value that I managed to get: FsNumber (declared it as financialNumber). What I need to add to the json: subjectName + subjectCode (they will be declared as companyName/companyCode). How do I access "Query" list with SubjectName/SubjectCode?
TEST
var queryResult = client.Execute<object>(request);
var data = JsonConvert.SerializeObject(queryResult.Data);
var jsonParse = JToken.Parse(data);
var fsObject = jsonParse.Value<JToken>("FinanceReportList");
var fsArray = fsObject.Value<JArray>("List");
foreach (var fs in fsArray)
{
var cfn = fs.Value<string>("FsNumber");
var queryObject = new DataQuery
{
financialNumber = cfn,
};
var queryObjectString = JsonConvert.SerializeObject(queryObject);
File.WriteAllText(#"C:\Users\TestAPI\myJsonWithValues.json", queryObjectString);
}
Data I get from the response:
{
"RequestDate": "2021-07-16",
"Message": "Active",
"ProductNumber": 666,
"Language": "EN",
"RequestId": "reqID666",
"Query": {
"SubjectCode": "MY-SUBJECT",
"SubjectName": "MY-NAME"
},
"FinanceReportList": {
"List": [
{
"FsNumber": "MY-NUMBER",
"Year": 2021,
So far I managed to get FsNumber to my myJsonWithValues.json file as this:
{"financialNumber":"MY-NUMBER","companyName":null,"companyCode":null}
What Im trying to do is, my json should look like
{"financialNumber":"MY-NUMBER","companyName":MY-NAME,"companyCode":MY-CODE}
You have to access "Query" object
var fsQuery = jsonParse.Value<JToken>("Query")
and use Children() method to access properties of "Query"
var children = fsQuery.Children();
It is a good practice to implement a class that encapsulates your resonse and deserialize it with JsonConvert.Deserialize eg.
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
Account account = JsonConvert.DeserializeObject<Account>(json);
Instead of using JObjects
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")
I am faced with a problem.
I want to deserialize a complex JSON response from a server, but I only need one part of it.
Here is an example:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
}
I also used Csharp2json to get the class objects that I need, I just modified the menu class according to my needs :
public class Menuitem
{
public string value { get; set; }
public string onclick { get; set; }
}
public class Popup
{
public IList<Menuitem> menuitem { get; set; }
}
public class Menu
{
public Popup popup { get; set; }
}
public class RootObjectJourney
{
public Menu menu { get; set; }
}
Now, how do I deserialize if I only need the popup value and his children?
You can actually utilize the Linq namespace of the NewtonSoft.Json and modify your code little bit to get only the "popup" elements from the JSON.
your class structure remains the same. Make sure you use the namespace(s)
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
then in your code once you have the JSON string with you, you can use the "JObject" static method "Parse" to parse the JSON, like
var parsedObject = JObject.Parse(jsonString);
This will give you the JObject with which you can access all your JSON Keys just like a Dictionary.
var popupJson = parsedObject["menu"]["popup"].ToString();
This popupJson now has the JSON only for the popup key.
with this you can use the JsonConvert to de- serialize the JSON.
var popupObj = JsonConvert.DeserializeObject<Popup>(popupJson);
this popupObj has only list of menuitems.
If you do not use Newtonsoft and are using System.Text.Json in .NET Core, you can use this:
var post = JsonDocument.Parse(stringifiedJson);
var cat = post.RootElement.GetProperty("category").GetString();
You see GetString here to cast the value to string, there are other overloads available to cast the json value to Int32 etc.
If the intend is to deserialize only one property, I generally perefer to use JsonPath due to its flexibility. Please check the code below
var jsonQueryString = "{ 'firstName': 'John',
'lastName' : 'doe',
'age' : 26,}";
JObject o = JObject.Parse(jsonQueryString);
JToken token= o.SelectToken("$.age");
Console.WriteLine(token);
If your Json is complex, you can use power of JsonPath.
you can check https://support.smartbear.com/readyapi/docs/testing/jsonpath-reference.html#examples for JsonPath detailed documentation and examples.
I also included example below for further usage information:
JObject o = JObject.Parse(#"{
'store': {
'book': [
{
'category': 'history',
'author': 'Arnold Joseph Toynbee',
'title': 'A Study of History',
'price': 5.50
},
...
]
},
'expensive': 10
}");
//gets first book object
Console.WriteLine(o.SelectToken("$..book[0]"));
//get first book's title
Console.WriteLine(o.SelectToken("$..book[0].title"));
// get authors of the books where the books are cheaper then 10 $
foreach (var token in o.SelectTokens("$..[?(#.price < 10)].author"))
Console.WriteLine(token);
.NET 5+
The solution is very simple:
using System.Text.Json;
var doc = JsonDocument.Parse(response.Content);
var popupJson= doc.RootElement.GetProperty("menu").GetProperty("popup");
I am developing facebook app in which i am fetching user's friend detail in as
dynamic result = client.Get("me/friends"); //it gives friend's data for id, name
it gives data in
{
"data": [
{
"name": "Steven",
"id": "57564897"
},
{
"name": "Andy",
"id": "8487581"
}
}
Now i would like to parse this data and store it. so that i can use it my way.
I was trying to parse it using JSON.NET and show the data in view as
var model = JsonConvert.DeserializeObject<FriendDetail>(result.data);
in the class :
public class FriendDetail
{
public string id { get; set; }
public string name { get; set; }
public FriendDetail(string i, string n)
{
id = i;
name = n;
}
}
Now so that i can pass the view as "return View(model)"
But its giving me error: The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<FBApp.Models.FBFriendDetail>(string)' has some invalid arguments
Why this error is occurring ?
Please help me to parse this json data.
Also is there any better way to parse and Store json data and also then show in view ?
Please help
You are trying to deserialize a list of FriendDetail objects into a single FriendDetail object. Try the following:
var jObject = JObject.Parse(result.ToString());
var model = JsonConvert.DeserializeObject<List<FriendDetail>>(jObject["data"].ToString());
EDIT
This is how I tested it:
var result =
#"{
""data"": [
{
""name"": ""Steven"",
""id"": ""57564897""
},
{
""name"": ""Andy"",
""id"": ""8487581""
}]
}";
var jObject = JObject.Parse(result.ToString());
var model = JsonConvert.DeserializeObject<List<FriendDetail>>(jObject["data"].ToString());