After Deserialize Object result have extra brackets - c#

Here is my data coming from ajax post.
string form = "[{\"id\": \"1\", \"name\": \"deneme\"},{\"id\": \"2\", \"name\": \"deneme2\"}]"
When I deserialize like this:
var data = JsonConvert.DeserializeObject(form);
The object is like this:
{ [{"id": 1, "name": "deneme"},{"id": 2, "name": "deneme2"}] }
How can I solve this problem?
Edit:
[HttpPost]
public HttpResponseMessage ImportFromExcel(string form, string controller, string action)
{
//form = "[{\"id\": \"1\", \"name\": \"deneme\"},{\"id\": \"2\", \"name\": \"deneme2\"}]"
ImportObject _importObject = new ImportObject();
_importObject.SchemaName = controller;
_importObject.TableName = action;
var deger = JsonConvert.DeserializeObject(form);
//deger = { [{"id": 1, "name": "deneme"},{"id": 2, "name": "deneme2"}] }
Utility.HttpPostJson(proUtil.GetConfigStr("ApiImportUrl", ""), "Import", JsonConvert.SerializeObject(_importObject));
return new HttpResponseMessage(HttpStatusCode.Created);
}
public class ImportObject
{
public string SchemaName { get; set; }
public string TableName { get; set; }
public List<string> DataSet { get; set; }
}

So you are deserialising into JSON.Net objects instead of using a proper concrete class structure. I would recommend doing something like this. First make a class to hold your data:
public class FormItem
{
public int Id { get; set; }
public string Name { get; set; }
}
Now deserialise into an IEnumerable<FormItem> like this:
var data = JsonConvert.DeserializeObject<IEnumerable<FormItem>>(form);
And now you can loop through it as you would any other enumerable:
foreach(var formItem in data)
{
Console.WriteLine($"Item with id of {formItem.Id} has a name of {formItem.Name}");
}

The Solution is:
var form = JsonConvert.DeserializeObject<List<object>>(comingData.ToString());
foreach (var item in form)
{
var cSharpClass = JsonConvert.DeserializeObject<dynamic>(item.ToString());
foreach (JProperty item2 in cSharpClass)
{
Console.WriteLine(item2.Name);
Console.WriteLine(item2.Value);
}
}

Related

Extract value from Json format in C#

I am trying to extract the objectId and displayName from below JSON format http result. But I have not been successful at all. can someone suggest me to extract objectId and displayName.
My code so far:
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://graph.windows.net/")
};
string URI = $"/{TenantID}/users?$filter=userPrincipalName%20eq%20'{EmailAddress}'&api-version=1.6";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + MSGraphToken);
HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
var HttpsResponse = await response.Content.ReadAsStringAsync();
dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);
UserDetails UserDetailsList = new UserDetails();
dynamic OdataResult = Result["value"];
if (Result != null)
{
UserDetailsList.DisplayName = OdataResult.displayName ?? "N/A";
UserDetailsList.ObjectID = OdataResult.objectId ?? "N/A";
}
return UserDetailsList;
JSON result:
{{
"value": [
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"objectId": "00000000-0000-0000-0000-000000000000",
"assignedPlans": [
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "RMSOnline",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "Adallom",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
],
"displayName": "Sachin Tendulkar (alt_sachint)",
"employeeId": "000000",
"userPrincipalName": "alt_sachint#pme.gbl.msidentity.com"
}
]
}}
just use Parse if you only need to get a couple of values. In this case you don't need to create classes
var json = await response.Content.ReadAsStringAsync();
var value = JObject.Parse(json)["value"];
string objectId = (string)value[0]["objectId"]; // 00000000-0000-0000-0000-000000000000
string displayName = (string)value[0]["displayName"]; // Sachin Tendulkar (alt_sachint)
and remove an extra "{ }" from the edges of your json
First of all your posted JSON is invalid, I have corrected it.
{
"value": [{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"objectId": "00000000-0000-0000-0000-000000000000",
"assignedPlans": [{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "RMSOnline",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "Adallom",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
}
],
"displayName": "Sachin Tendulkar (alt_sachint)",
"employeeId": "000000",
"userPrincipalName": "alt_sachint#pme.gbl.msidentity.com"
}]
}
Then you should deserialize the json to a class object.
Root obj = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class AssignedPlan
{
public DateTime assignedTimestamp { get; set; }
public string capabilityStatus { get; set; }
public string service { get; set; }
public string servicePlanId { get; set; }
}
public class Root
{
public List<Value> value { get; set; }
}
public class Value
{
[JsonProperty("odata.type")]
public string odatatype { get; set; }
public string objectType { get; set; }
public string objectId { get; set; }
public List<AssignedPlan> assignedPlans { get; set; }
public string displayName { get; set; }
public string employeeId { get; set; }
public string userPrincipalName { get; set; }
}
So you can get the List of Value by obj.value which is a List of Value. Value class has properties objectId and employeeId .
You can use foreach or for or LINQ to fetch these properties accordingly.
you can get using dynamic also but i recommended to use strong type
Logic to get values
Using Strong Type
private void ReadJson()
{
string json = #"{""value"":[{""odata.type"":""Microsoft.DirectoryServices.User"",""objectType"":""User"",""objectId"":""00000000 - 0000 - 0000 - 0000 - 000000000000"",""assignedPlans"":[{""assignedTimestamp"":""2022 - 09 - 06T20: 38:49Z"",""capabilityStatus"":""Enabled"",""service"":""RMSOnline"",""servicePlanId"":""00000000 - 0000 - 0000 - 0000 - 000000000000""},{""assignedTimestamp"":""2022 - 09 - 06T20: 38:49Z"",""capabilityStatus"":""Enabled"",""service"":""Adallom"",""servicePlanId"":""00000000 - 0000 - 0000 - 0000 - 000000000000""},],""displayName"":""Sachin Tendulkar(alt_sachint)"",""employeeId"":""000000"",""userPrincipalName"":""alt_sachint #pme.gbl.msidentity.com""}]}";
var response = JsonConvert.DeserializeObject<Result>(json);
var objid = response.value[0].objectId;
var displayname = response.value[0].displayName;
// using for loop
foreach( var res in response.value)
{
objid = res.objectId;
displayname = res.displayName;
}
// you can use linq if you need object id and display name for specific condition
}
Classes
public class Result
{
public List<Response> value { get; set; }
}
public class Response
{
public string objectId { get; set; }
public string displayName { get; set; }
[JsonProperty("odata.type")]
public string odatatype { get; set; }
public string objectType { get; set; }
public List<AssignedPlan> assignedPlans { get; set; }
public string employeeId { get; set; }
public string userPrincipalName { get; set; }
}
public class AssignedPlan
{
public DateTime assignedTimestamp { get; set; }
public string capabilityStatus { get; set; }
public string service { get; set; }
public string servicePlanId { get; set; }
}
using dynamic
// 2. using dynamic
dynamic Result = JsonConvert.DeserializeObject<object>(json);
JArray jsonObject = JArray.FromObject(Result["value"]);
//JArray jsonObject = JArray.Parse(Result["value"]);
foreach (JObject content in jsonObject.Children<JObject>())
{
// you can get value from one of the approach
// 1. Approach
foreach (JProperty prop in content.Properties().Where(p => p.Name == "objectId"))
{
objid = prop.Value.ToString();
}
foreach (JProperty prop in content.Properties().Where(p => p.Name == "displayName"))
{
displayname = prop.Value.ToString();
}
// 2. Apprach
foreach (JProperty prop in content.Properties())
{
if (prop.Name == "objectId")
{
objid = prop.Value.ToString();
}
else if(prop.Name == "displayName")
{
displayname = prop.Value.ToString();
}
}
}
you can get value by following #Serge answer using dynamic if it is always one object in response(value node) but as per your sample it is array so you need to use Jarray or loop to get each value.

C#, JSON.net Loop through and store Jobject objects

New to both C# and to using JSON. Trying to make something that works with some JSON from a web API in the following format. Would like to loop through and store the secondUser_id and and the status for later use.
{
"user_list": [
{
"user_id": "12345678910",
"secondUser_id": "5428631729616515697",
"member_since": "1521326679",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
},
{
"user_id": "11345638910",
"secondUser_id": "5428631729616515697",
"member_since": "1521326679",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
},
{
"user_id": "13452578910",
"secondUser_id": "12390478910",
"member_since": "12316578910",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
}
],
"returned": 3
}
string jsonUrl = GetJSON("url");
JObject UsersJObject = JObject.Parse(jsonUrl);
JToken user = UsersJObject["user_list"].First["secondUser_id"];
Console.WriteLine("User ID: " + user);
This will get the first entry but I'm not sure what to use for a enumerator?
try something like this:
foreach (var obj in UsersJObject["user_list"] as JArray)
{
Console.WriteLine(obj["secondUser_id"]);
}
You can iterate over elements of a JArray, and user_list will be of that type, cast it and you can iterate it in a foreach loop.
I will recommend you to use JsonConvert.DeserializeObject<T>.
This can help you to use objects easily
public class UserList
{
public string user_id { get; set; }
public string secondUser_id { get; set; }
public string member_since { get; set; }
public string member_since_date { get; set; }
public string function { get; set; }
public string rank_int { get; set; }
public string status { get; set; }
}
public class JsonData
{
public List<UserList> user_list { get; set; }
public int returned { get; set; }
}
Use like this.
string jsonUrl = GetJSON("url");
JsonData UsersJObject = JsonConvert.DeserializeObject<JsonData>(jsonUrl);
foreach (var obj in UsersJObject.user_list)
{
Console.WriteLine(obj.secondUser_id);
}

Parsing Array of objects JSON in C#

My JSON Input is below. Sry it is too long
{
"status":{
"success":[
{
"User":{
"id":"1377",
"username":"Dr.Hema Sathish",
"username_url":"dr-hema-sathish",
"firstname":null,
"lastname":null,
"email":"madurai#sancheclinic.com",
"password":"6c7ab07e828828206e3d7c56c3c35cfd383960cd",
"user_level":"doctor"
},
"Speciality":{
"id":"2",
"name":"Dermatology(Skin Specialist)",
"slug":"dermatology-skin-specialist",
"image":"1438693213.png",
"status":"1",
"created":"2015-07-08 03:35:57",
"modified":"2016-09-13 13:58:36"
}
}
]
}
}
I have downloaded JSON String from URL Successfully.
static void main
{
using (var webClient = new System.Net.WebClient())
{
string json = webClient.DownloadString("http://myURL/");
Console.WriteLine(json.ToString());
}
}
Now I have to get User and Speciality objects. Its confusing to parse Array of Objects Json. How to parse it?
I have tried Deserialization. But it does not work.
How to parse it?
Your json is invalid...here is correct json
{
"status": {
"success": [{
"User": {
"id": "1377",
"username": "Dr.Hema Sathish"
},
"Speciality": {
"id": "2",
"name": "Dermatology(Skin Specialist)"
}
},
{
"User": {
"id": "1390",
"username": "Dr.Nichita Balaji"
},
"Speciality": {
"id": "2",
"name": "Dermatology(Skin Specialist)"
}
}
]
}
}
You can create below classes to deserialize it using Newtonsoft
public class User
{
public string id { get; set; }
public string username { get; set; }
}
public class Speciality
{
public string id { get; set; }
public string name { get; set; }
}
public class Success
{
public User User { get; set; }
public Speciality Speciality { get; set; }
}
public class Status
{
public List<Success> success { get; set; }
}
public class RootObject
{
public Status status { get; set; }
}
Here is the code to deserialize it
string json =
" {\r\n \t\"status\": {\r\n \t\t\"success\": [{\r\n \t\t\t\t\"User\": {\r\n \t\t\t\t\t\"id\": \"1377\",\r\n \t\t\t\t\t\"username\": \"Dr.Hema Sathish\"\r\n \t\t\t\t},\r\n \t\t\t\t\"Speciality\": {\r\n \t\t\t\t\t\"id\": \"2\",\r\n \t\t\t\t\t\"name\": \"Dermatology(Skin Specialist)\"\r\n \t\t\t\t}\r\n \t\t\t},\r\n \t\t\t{\r\n \t\t\t\t\"User\": {\r\n \t\t\t\t\t\"id\": \"1390\",\r\n \t\t\t\t\t\"username\": \"Dr.Nichita Balaji\"\r\n \t\t\t\t},\r\n \t\t\t\t\"Speciality\": {\r\n \t\t\t\t\t\"id\": \"2\",\r\n \t\t\t\t\t\"name\": \"Dermatology(Skin Specialist)\"\r\n \t\t\t\t}\r\n\r\n \t\t\t}\r\n \t\t]\r\n \t}\r\n }";
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
var successes = rootObject.status.success;
var specialityObjects = successes.Select(success => success.Speciality).ToList();
var users = successes.Select(success => success.User).ToList();
Console.WriteLine(users[0].id + " " + users[0].username);
Console.WriteLine(users[1].id + " " + users[1].username);
Console.WriteLine(specialityObjects[0].id + " " + specialityObjects[0].name);
Console.WriteLine(specialityObjects[1].id + " " + specialityObjects[1].name);
Console.ReadLine();
//OUTPUT
1377 Dr.Hema Sathish
1390 Dr.Nichita Balaji
2 Dermatology(Skin Specialist)
2 Dermatology(Skin Specialist)
You have to create classes according to JSON data set :
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
public class Speciality
{
public int Id { get; set; }
public string Name { get; set; }
}
Then, you should be able to Deserialize using JSON .NET library
string json = webClient.DownloadString("http://myURL/");
User u = JsonConvert.DeserializeObject<User>(json);
There may be other library available, nonetheless this one is working fine (and is available as NuGET package).
Please note this is only a sample, your code will miss several classes to properly parse your JSON (Status class, etc.).

Find a value from the json string in c#

This is my json string :
{"loginAccounts": [
{
"name": "abc",
"accountId": "123456",
"baseUrl": "https://abc.defghi.com/test/t12/remark/123456",
"isDefault": "true",
"userName": "Ceilina James",
"userId": "7c5bat57-850a-5c93-39eb-2015ai9o8822",
"email": "abc#test.com",
"siteDescription": ""
}
]}
I need "baseUrl" value. How to find it in the C# ?
You could use a JSON serializer such as the JavaScriptSerializer class to deserialize this JSON string to a C# class and then extract the required value. For example you could have the following model:
public class SomeModel
{
public LoginAccount[] LoginAccounts { get; set; }
}
public class LoginAccount
{
public string Name { get; set; }
public string AccountId { get; set; }
public string BaseUrl { get; set; }
public string IsDefault { get; set; }
...
}
and then:
string json = "... your JSON string comes here ...";
var serializer = new JavaScriptSerializer();
string json = ...
var model = (SomeModel)serializer.Deserialize(json);
foreach (var account in model.LoginAccounts)
{
string baseUrl = account.BaseUrl;
...
}
Using Json.Net
foreach (var acc in JObject.Parse(json)["loginAccounts"])
{
Console.WriteLine(acc["baseUrl"]);
}

deserialization with the JavaScriptSerializer is missing fields

The fields are getting ignored. I'm successfully getting back a list of 2 objects, but none of the fields are populated. What am I doing wrong? (Unfortunately I don't have control over the json format. It arrives in exactly this structure.
using System.Web.Script.Serialization;
public void myMethod {
string myContent = #"
[
{
"my_object": {
"city": "city 1",
"myAge": 15
}
},
{
"my_object": {
"city": "city 2",
"myAge": 18
}
}
]";
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<my_object> list = serializer.Deserialize<List<my_object>>(myContent);
}
public class json_content {
public string city { get; set; }
public int myAge { get; set; }
}
This code solves your problem:
public void myMethod()
{
string myContent = #"
[
{
""json_content"": {
""city"": ""city 1"",
""myAge"": 15
}
},
{
""json_content"": {
""city"": ""city 2"",
""myAge"": 18
}
}
]";
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<wrapper> list = serializer.Deserialize<List<wrapper>>(myContent);
}
public class wrapper
{
public json_content json_content { get; set; }
}
public class json_content
{
public string city { get; set; }
public int myAge { get; set; }
}
You have list of objects with one property json_content in your JSON, but expect list directly containing json_content objects.
Most likely fix is to remove intermediate object from JSON (if you control it):
[
{
"city": "city 1",
"myAge": 15
},...
];
If you don't control JSON add outer class:
class JsonOuterContent
{
public JsonContent json_content;
}
List<JsonOuterContent> list = serializer
.Deserialize<List<JsonOuterContent>>(myContent);

Categories