I want to get "id" "gender", "name", "picture" from a this json response string
{
"data": [{
"name": "XXX",
"gender": "male",
"id": "528814",
"picture": {
"data": {
"is_silhouette": false,
"url": "https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc3\/v\/t1.0-1\/p50x50\/551182_10152227358459008__n.jpg?oh=983b70686285c2f60f71e665ace8ed5f&oe=54C1220C&__gda__=1422017140_998fbe013c4fe191ccadfdbc77693a76"
}
}
}
string[] data = friendsData.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries).ToArray();
foreach (string d in data)
{
try
{
FacebookFriend f = new FacebookFriend
{
id = d.Substring("\"id\":\"", "\""),
gender = d.Substring("gender\":\"", "\""),
name = d.Substring("name\":\"", "\""),
picture = d.Substring("\"picture\":{\"data\":{\"url\":\"", "\"").Replace(#"\", string.Empty)
};
FacebookFriendList.Add(f);
}
catch
{
continue;
}
}
This code looks bad if the json data changes then you need to modify your logic accordingly. I would suggest you to serialize and deserialize the model data using Json serialization.
Model:
public class SerializationModel
{
public Data Data { get; set; }
}
public class Data
{
public string Name { get; set; }
public string Gender { get; set; }
public string Id { get; set; }
public Picture Picture { get; set; }
}
public class Picture
{
public PictureData Data { get; set; }
}
public class PictureData
{
public bool is_silhouette { get; set; }
public string url { get; set; }
}
Serialize your data to get the json output is like,
SerializationModel serializationModel = new SerializationModel
{
Data = new Data
{
Gender = "mALE",
Id = "88",
Name = "User",
Picture = new Picture
{
Data = new PictureData
{
is_silhouette = true,
url = "www.google.com"
}
}
}
};
string serializedString = Newtonsoft.Json.JsonConvert.SerializeObject(serializationModel);
which would yield the below result,
{"Data":{"Name":"User","Gender":"mALE","Id":"88","Picture":{"Data":{"is_silhouette":true,"url":"www.google.com"}}}}
To deserialize the json data back to the model,
SerializationModel sm = Newtonsoft.Json.JsonConvert.DeserializeObject<SerializationModel>(serializedString);
Then you can get the required values from the model itself.
Related
I have a situation while working with a JSON response from an API. To give a background, I am consuming an API from a source using a REST API using 3.5 .net framework.
Below is the part of the JSON output and I am kind of struggling to use it.
a)
"value": {
"Description": "Total Calculated things",
"2018": "5,820,456 ",
"2019": "2,957,447 "
}
The last 2 elements are dynamic, those are tend to change in API response. I was expecting the format like I have mentioned below, but at this point of given time the source provider is not able to change it as the API is used in many other different programs. And Changing the things in the source API will make other program owners to change.
b)
"value": {
"Description": "Total Calculated EQUITY AND LIABILITIES",
"YearData": [ {
"Data": "5,820,456",
"Year": "2018"
},
{
"Data": "2,957,447 ",
"Year": "2019"
} ]
}
Is there any way to overcome such thing> Any way to convert a to b?
EDIT
#Xerillio , Thanks . How can I achieve the same using below JSON format.
var json = #"
{
""entityData"": [
{
""name"": ""Statement of Comprehensive Income"",
""subattrOutput"": [
{
""name"": ""Sales"",
""subattrOutput"": [],
""value"": {
""Description"": ""Sales "",
""2018"": ""8,704,888 "",
""2019"": ""4,760,717 ""
},
""score"": ""99.5"",
""valuetype"": ""object""
},
{
""name"": ""Cost of goods sold"",
""subattrOutput"": [],
""value"": {
""Description"": ""Cost of sales "",
""2018"": ""(6,791,489) "",
""2019"": ""(3,502,785) ""
},
""score"": ""99.75"",
""valuetype"": ""object""
}
],
""value"": null,
""score"": ""98.63"",
""valuetype"": ""object""
}
]
}";
I wish this was more easy, but i just got it here:
class Program
{
static async Task Main(string[] args)
{
string json1 = #"{""value"": {""Description"": ""Total Calculated things"",""2018"": ""5,820,456 "",""2019"": ""2,957,447 ""}}";
string json2 = #"{""value"": {""Description"": ""Total Calculated EQUITY AND LIABILITIES"",""YearData"": [ {""Data"": ""5,820,456"",""Year"": ""2018""},{""Data"": ""2,957,447 "",""Year"": ""2019""} ]}}";
var obj1 = JsonConvert.DeserializeObject<ObjectResult>(json1);
var obj2 = JsonConvert.DeserializeObject<ObjectResult>(json2);
var res1 = CastObject<Result1>(obj1.Value.ToString());
var res2 = CastObject<Result2>(obj2.Value.ToString());
var invalidRes1 = CastObject<Result1>(obj2.Value.ToString());
var invalidRes2 = CastObject<Result2>(obj1.Value.ToString());
Console.WriteLine(res1);
Console.WriteLine(res2);
}
public static T CastObject<T>(string obj)
{
return !TryCastObject(obj, out T result) ? default : result;
}
public static bool TryCastObject<TOut>(string objToCast, out TOut obj)
{
try
{
obj = JsonConvert.DeserializeObject<TOut>(objToCast);
return true;
}
catch
{
obj = default;
return false;
}
}
}
public class ObjectResult
{
public object Value { get; set; }
}
public class Result1
{
[JsonProperty(PropertyName = "description")] public string Description { get; set; }
[JsonProperty(PropertyName = "2018")] public string _2018 { get; set; }
[JsonProperty(PropertyName = "2019")] public string _2019 { get; set; }
}
public class Result2
{
[JsonProperty(PropertyName = "Description")] public string Description { get; set; }
[JsonProperty(PropertyName = "YearData")] public List<YearData> YearData { get; set; }
}
public class YearData
{
[JsonProperty(PropertyName = "Data")] public string Data { get; set; }
[JsonProperty(PropertyName = "Year")] public string Year { get; set; }
}
It is A LOT of work and sincerely, as there more nodes in the json i think that using JObject is the best option, and you will have to do a deserealization in more than 1 step :(
Depending on how large the JSON structure is you could deserialize it into a Dictionary and manually map it to the proper format:
var json = #"
{
""value"": {
""Description"": ""Total Calculated things"",
""2018"": ""5,820,456 "",
""2019"": ""2,957,447 ""
}
}";
var badObj = JsonSerializer.Deserialize<BadFormat>(json);
var result = new WrapperType
{
Value = new ProperlyFormattedType()
};
foreach (var pair in badObj.Value)
{
if (pair.Key == "Description")
{
result.Value.Description = pair.Value;
}
else if (int.TryParse(pair.Key, out int _))
{
result.Value.YearData
.Add(new DatedValues
{
Year = pair.Key,
Data = pair.Value
});
}
}
// Data models...
public class BadFormat
{
[JsonPropertyName("value")]
public Dictionary<string, string> Value { get; set; }
}
public class WrapperType
{
public ProperlyFormattedType Value { get; set; }
}
public class ProperlyFormattedType
{
public string Description { get; set; }
public List<DatedValues> YearData { get; set; } = new List<DatedValues>();
}
public class DatedValues
{
public string Year { get; set; }
public string Data { get; set; }
}
See an example fiddle here.
Need a JSON response like this:
{
"statusCode": 200,
"errorMessage": "Success",
"Employees": [
{
"empid": "7228",
"name": "Tim",
"address": "10815 BALTIMORE",
},
{
"empid": "7240",
"name": "Joe",
"address": "10819 Manasas",
}
]
}
Model Class:
public class EmployeeList
{
public string empid { get; set; }
public string name { get; set; }
public string address { get; set; }
}
public class Employee
{
public int statusCode { get; set; }
public string errorMessage{ get; set; }
public List<EmployeeList> Employees { get; set; }
}
Controller is like this:
List<Models.Employee> emp = new List<Models.Employee>();
//call to SP
if (rdr.HasRows)
{
var okresp = new HttpResponseMessage(HttpStatusCode.OK)
{
ReasonPhrase = "Success"
};
Models.Employee item = new Models.Employee();
{
item.statusCode = Convert.ToInt32(okresp.StatusCode);
item.errorMessage = okresp.ReasonPhrase;
while (rdr.Read())
{
item.Employees = new List<EmployeeList>{
new EmployeeList
{
empid = Convert.ToString(rdr["empid"]),
name = Convert.ToString(rdr["name"]),
address = Convert.ToString(rdr["address"])
}};
}
};
emp.add(item);
// return response
What should be my controller class code to create JSON array response while I read data from reader?
I am not able to get the loop part of creating JSON array in response file. Am I assigning the values in While loop incorrectly?
After your while (rdr.Read()), you reset item.Employees with a new List<EmployeeList> at every data. So you will be getting the last element every time.
Move your list initialisation outside of the loop and use the add method.
item.Employees = new List<EmployeeList>();
while (rdr.Read())
{
item.Employees.Add(
new EmployeeList
{
empid = Convert.ToString(rdr["empid"]),
name = Convert.ToString(rdr["name"]),
address = Convert.ToString(rdr["address"])
});
}
I am trying to create a web API which calls the other service and returns a array of response. The called service returns the response. I am able to get the individual item from the called service. But not sure how to build array of items and return as response from the API I am creating.
The JSON returned from the service looks like
{
"cr_response": {
"details": [{
"name": "Req",
"fields": [{
"value": "Prj0\r\nPrj1",
"name": "Project"
},
{
"value": "October 13, 2017 14:18",
"name": "Submitted"
},
{
"value": "John",
"name": "Rec Name"
}
]
}],
"cr_metadata": {}
}
}
And the POCO class looks like
public class Field
{
public string value { get; set; }
public string name { get; set; }
}
public class Detail
{
public string name { get; set; }
public List<Field> fields { get; set; }
}
public class CrMetadata
{
}
public class CrResponse
{
public List<Detail> details { get; set; }
public CrMetadata cr_metadata { get; set; }
}
public class RootObject
{
public CrResponse cr_response { get; set; }
}
Below is the code for calling the service and retrieving the response from the services
var response = await iLab_client.GetAsync(uri);
var datafile = await response.Content.ReadAsStringAsync();
var returnDataObj = JsonConvert.DeserializeObject<DTO.RootObject>(datafile);
foreach (var form in returnDataObj.cr_response.details)
{
name_response = form.name;
return Ok(name_response);
}
Here I can access the name from the details but not sure how can I access the all the name and value from the fields and construct it in a array. And send it as a JSON response.
I tried like
foreach (var form in returnDataObj.cr_response.details)
{
var id_response = form.fields;
return Ok(id_response);
}
But it throws error like
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content
type 'application/xml; charset=utf-8'.
</ExceptionMessage>
System.InvalidOperationException
To return array from Web API you need to fill your array and return it outside foreach loop:
var list = new List<string>();
foreach (...){
var name = ...
list.Add(name);
}
return Ok(list.ToArray()); // or just return Ok(list);
This is how to deserialize JSON to POCO and get the list of the names:
[TestMethod]
public void TestJsonToPocoAndGetNames()
{
const string Json = #"
{
""cr_response"": {
""details"": [{
""name"": ""Req"",
""fields"": [{
""value"": ""Prj0\r\nPrj1"",
""name"": ""Project""
},
{
""value"": ""October 13, 2017 14:18"",
""name"": ""Submitted""
},
{
""value"": ""John"",
""name"": ""Rec Name""
}
]
}],
""cr_metadata"": {}
}
}
";
var settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
var response = JsonConvert.DeserializeObject<RootJsonObject>(Json, settings);
var names = new List<string>();
foreach (var detail in response.CrResponse.Details)
{
names.Add(detail.Name);
foreach (var field in detail.Fields)
{
names.Add(field.Name);
}
}
Assert.AreEqual(
"Req, Project, Submitted, Rec Name",
string.Join(", ", names.ToArray()));
}
POCO classes:
public class RootJsonObject
{
[JsonProperty("cr_response")]
public CrResponse CrResponse { get; set; }
}
public class CrResponse
{
[JsonProperty("cr_metadata")]
public CrMetadata CrMetadata { get; set; }
[JsonProperty("details")]
public Detail[] Details { get; set; }
}
public class CrMetadata
{
}
public class Detail
{
[JsonProperty("fields")]
public Field[] Fields { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class Field
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
I need to parse a JSON, I am already parsing the first part of the record but I am having a problem with a sub record. This is my code:
List<JToken> results = new List<JToken>();
List<JToken> results2 = new List<JToken>();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
results = JObject.Parse(result).SelectToken("record").ToList();
}
List<Record> users = new List<Record>();
foreach (JObject token in results)
{
Record user = new Record();
user.id = Int32.Parse(token["id"].ToString());
user.full_name = token["full_name"].ToString();
user.email = token["email"].ToString();
//role.RoleName = token.SelectToken("name").ToString();
}
That's working perfectly but I have issues parsin a string that's a bit deeper. This is the JSON:
{
"record": [
{
"id": 2,
"institution_id": 1,
"full_name": "",
"email": "",
"role_id": 2,
"created": "2015-01-13 01:18:52.370379",
"updated": "2015-01-22 23:58:44.103636",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "Test Branch"
}
}
]
}
I want to get the "branch_name" inside Branch_by_branch_id. How can I access it with Jobject?
If your JSON is this
{
"record": [
{
"id": 26,
"full_name": "",
"email": "",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "NAME"
}
}
]
}
Have classes like this:
public class BranchByBranchId
{
public int id { get; set; }
public int institution_id { get; set; }
public string branch_name { get; set; }
}
public class Record
{
public int id { get; set; }
public string full_name { get; set; }
public string email { get; set; }
public int branch_id { get; set; }
public BranchByBranchId Branch_by_branch_id { get; set; }
}
public class RootObject
{
public List<Record> record { get; set; }
}
Then parse it and retrieve the value like this.
var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;
I always prefer to access my JSON objects like this, because I like having my objects as native C# classes. The classes were generated by json2csharp.
How to get an item value of json using C#?
json:
[{
ID: '6512',
fd: [{
titie: 'Graph-01',
type: 'graph',
views: {
graph: {
show: true,
state: {
group: 'DivisionName',
series: ['FieldWeight', 'FactoryWeight', 'Variance'],
graphType: 'lines-and-points'
}
}
}
}, {
titie: 'Graph-02',
type: 'Graph',
views: {
graph: {
show: true,
state: {
group: 'DivisionName',
series: ['FieldWeight', 'FactoryWeight', 'Variance'],
graphType: 'lines-and-points'
}
}
}
}]
}, {
ID: '6506',
fd: [{
titie: 'Map-01',
type: 'map',
views: {
map: {
show: true,
state: {
kpiField: 'P_BudgetAmount',
kpiSlabs: [{
id: 'P_BudgetAmount',
hues: ['#0fff03', '#eb0707'],
scales: '10'
}]
}
}
}
}]
}]
Above mentioned one is json, Here titie value will be get in a list
please help me...
My code is:
string dashletsConfigPath = Url.Content("~/Content/Dashlets/Dashlets.json");
string jArray = System.IO.File.ReadAllText(Server.MapPath(dashletsConfigPath));
List<string> lists = new List<string>();
JArray list = JArray.Parse(jArray);
var ll = list.Select(j => j["fd"]).ToList();
Here json will be converted in to JArray then
li got fd details then we got tite details on a list
If you just want a List<string> of the "titie" (sic) property values, this should work, using SelectMany:
List<string> result = list.SelectMany(
obj => obj["fd"]
.Select(inner => inner["titie"].Value<string>()))
.ToList()
This assumes that the JSON you posted is made valid by quoting property names.
I would recommend creating a class for your objects and use a DataContractSerializer to deserialize the JSON string.
[DataContract]
public class Container
{
[DataMember(Name="ID")]
public string ID { get; set; }
[DataMember(Name="fd")]
public Graph[] fd { get; set; }
}
[DataContract]
public class Graph
{
[DataMember(Name="title")]
public string Title { get; set; }
[DataMember(Name="type")]
public string Type { get; set; }
}
etc.
This will give you strongly typed classes around your JSON.
I'm not sure how you intend to use the data but you can collect all the titie values from your objects like this:
var arr = JArray.Parse(json);
var query =
from JObject obj in arr
from JObject fd in obj["fd"]
select new
{
Id = (string)obj["ID"],
Titie = (string)fd["titie"],
};
You can use json.net to deserialize json string like this:
public class Item
{
public string ID { get; set; }
public List<FD> fd { get; set; }
}
public class FD
{
public string titie { get; set; }
public string type { get; set; }
public Views views { get; set; }
}
public class Views
{
public Graph graph { get; set; }
}
public class Graph
{
public bool show { get; set; }
public State state { get; set; }
}
public class State
{
public string group { get; set; }
public string[] series { get; set; }
public string graphType { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = #"..."; //your json string
var Items = JsonConvert.DeserializeObject<List<Item>>(json);
List<string> tities = new List<string>();
foreach (var Item in Items)
{
foreach (var fd in Item.fd)
{
tities.Add(fd.titie);
}
}
}
}
First thing is your json format invalid. get the valid json below.
[{
"ID": "6512",
"fd": [{
"titie": "Graph-01",
"type": "graph",
"views": {
"graph": {
"show": true,
"state": {
"group": "DivisionName",
"series": ["FieldWeight", "FactoryWeight", "Variance"],
"graphType": "lines-and-points"
}
}
}
}, {
"titie": "Graph-02",
"type": "Graph",
"views": {
"graph": {
"show": true,
"state": {
"group": "DivisionName",
"series": ["FieldWeight", "FactoryWeight", "Variance"],
"graphType": "lines-and-points"
}
}
}
}]
}, {
"ID": "6506",
"fd": [{
"titie": "Map-01",
"type": "map",
"views": {
"map": {
"show": true,
"state": {
"kpiField": "P_BudgetAmount",
"kpiSlabs": [{
"id": "P_BudgetAmount",
"hues": ["#0fff03", "#eb0707"],
"scales": "10"
}]
}
}
}
}]
}]
And if you want to read items as separate strings use following code.
JArray jObject = JArray.Parse(json);
var ll = jObject.ToList();
You can use Newtonsoft Json Library.
Deserialize your json string with the model objects below
public class JsonWrapper
{
public string ID { get; set; }
public List<Fd> fd { get; set; }
}
public class Fd
{
public string titie { get; set; }
public string type { get; set; }
public Views views { get; set; }
}
public class Views
{
public Graph graph { get; set; }
}
public class Graph
{
public bool show { get; set; }
public State state { get; set; }
}
public class State
{
public string group { get; set; }
public List<string> series { get; set; }
public string graphType { get; set; }
}
Declare on object of JsonWrapper class and deserialize the json string to it.
JsonWrapper jsonWrapper = new JsonWrapper();
jsonWrapper = (JsonWrapper)JsonConvert.DeserializeObject(jsonString, jsonWrapper.getType());
Then you can access all the lists and properties from the jsonWrapper object.