Find a value from the json string in c# - 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"]);
}

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.

How to display welcome message dynamically in c#?

I am coming to a problem where I am returning a whole guid from my rest api, however I just want to get the get the WelcomeMessage to show dynamically instead of hardcoding it. can anyone help me solve this issue. thanks for the help.
I have a child name Tests above the guid
Json:
{
"42f6be79-443b-4845-8549-865af9e74988": {
"Active": true,
"CompletedMessage": "Placeholder",
"CreatedBy": "",
"Description": "Placeholder",
"DisplayName": "Placeholder1",
"ID": "be193200-c277-48bd-90ab-796e869f2e0b",
"QuestionsIDs": [
"bd341962-6c7f-459d-88ea-86aa7186840a",
"bd341962-6c7f-459d-88ea-86aa7186840a"
],
"WelcomeMessage": "Placeholder3"
}
}
Code:
public Text welcomeMessage;
private async void welcomeMessage()
{
Dictionary<string, Questions> questionDictionary = new Dictionary<string, Questions>();
string json = #"{https://PROJECT_URL.firebaseio.com/Tests/WelcomeMessage.json";
questionDictionary = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json);
foreach (Questions question in questionDictionary.Values)
{
Guid[] guids = question.QuestionsIDs;
string welcomeMessage = question.WelcomeMessage;
welcomeMessageShown = GetComponent<Text>();
welcomeMessageShown.text = welcomeMessage.ToString();
}
First create a class that matches your object. Lets say Question
public partial class Question
{
[JsonProperty("Active")]
public bool Active { get; set; }
[JsonProperty("CompletedMessage")]
public string CompletedMessage { get; set; }
[JsonProperty("CreatedBy")]
public string CreatedBy { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("DisplayName")]
public string DisplayName { get; set; }
[JsonProperty("ID")]
public Guid Id { get; set; }
[JsonProperty("QuestionsIDs")]
public Guid[] QuestionsIDs { get; set; }
[JsonProperty("WelcomeMessage")]
public string WelcomeMessage { get; set; }
}
Since our json is a key value pair we need to deserialize it to a Dictionary
Our dictionary definition will be
Dictionary<string, Question> questionDictionary = new Dictionary<string, Question>();
Now using Newtonsoft.Json we can deserialize this to our dictionary.
string json = #"{
'42f6be79-443b-4845-8549-865af9e74988': {
'Active': true,
'CompletedMessage': 'Placeholder',
'CreatedBy': '',
'Description': 'Placeholder',
'DisplayName': 'Placeholder1',
'ID': 'be193200-c277-48bd-90ab-796e869f2e0b',
'QuestionsIDs': [
'bd341962-6c7f-459d-88ea-86aa7186840a',
'bd341962-6c7f-459d-88ea-86aa7186840a'
],
'WelcomeMessage': 'Placeholder3'
}
}";
Dictionary<string, Question> questionDictionary = JsonConvert.DeserializeObject<Dictionary<string, Question>>(json);
foreach (Question question in questionDictionary.Values)
{
Guid[] guids = question.QuestionsIDs; // Do whatever you want with it
string welcomeMessage = question.WelcomeMessage;
}

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);
}

Deserialize JSON object xamarin C#

I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
My JSON Object Class:
public class jsonobjectclass
{
public class User
{
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public List<UserGroups> user_groups { get; set; }
}
public class UserGroups
{
[JsonProperty("10")]
public string Student { get; set; }
[JsonProperty("15")]
public string Tutor { get; set; }
[JsonProperty("11")]
public string Parent { get; set; }
}
public class Token
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string token_type { get; set; }
public string scope { get; set; }
public string refresh_token { get; set; }
public string error { get; set; }
}
public class UserResponse
{
public string msg { get; set; }
public List<User> data { get; set; }
public bool error { get; set; }
}
}
My Code to Deserialize JSON:
public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
{
var jsonObject = new jsonobjectclass.UserResponse();
string readHttpResponse;
using (var httpClient = new HttpClient())
{
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
{
httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObject = JObject.Parse(readHttpResponse);
try
{
jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
}
catch(Exception ex)
{
string excep = ex.ToString();
readHttpResponse = excep;
}
}
}
}
return jsonObject;
}
My JSON String:
{{
"msg": null,
"data": {
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
},
"error": false
}}
Please Help me to solve this.
Thanks,
Rokesh
You have mismatch between the string and the object you are trying to deserialize into. The data object is not an array and there is an additional nested object which is not named in the JSON separately containing the msg field and the user data, but the error field is not part of that object:
As the comments have pointed out the JSON is not valid as is, so if you have control of the source I would fix that.
If not you could implement a reader and parse it as token by token, something like this:
using (var response = await client.GetAsync(_url, HttpCompletionOption.ResponseHeadersRead))
using (var stream = await response.Content.ReadAsStreamAsync())
using (var streamReader = new StreamReader(stream))
using (var reader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Start:
// code to handle it
break;
case JsonToken.PropertyName:
// code to handle it
break;
// more options
}
}
}
although this approach is more fragile. You can take a look at The JSON.Net JsonToken docs for more info.
Based on your comment and using https://jsonlint.com/ the response string
"{\"msg\":null,\"data\":{\"name\":\"geoit\",\"email\":\"roke‌​sh#geoit.in\",\"phon‌​e\":null,\"current_g‌​roup\":\"11\",\"user‌​_groups\":{\"11\":\"‌​Parent\"}},\"error\"‌​:false}"
is actually valid JSON, but the object is a little bizarre. I think it looks something like this in C#
public class UserGroup
{
public string 11 { get; set; }
}
public class UserData {
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public UserGroup user_groups { get; set; }
}
public class ResponseObject
{
public string msg { get; set; }
public UserData data { get; set; }
public bool error { get; set; }
}
It should be an array the opening and closing brackets should be square brackets:
[
{ "msg": null,"data":
[ {
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups":
[{
"11": "Parent"
}
]
}
],
"error": false
}
]
Also in your code, you dont need var jObject = JObject.Parse(readHttpResponse); since the readHttpResponse is already a JSON string which you can deserialzie into an object.
Aplogies for the misleading answer earlier. The object you need to make array is the 'data' property of the response JSON. You have to get it from the server side as your Domainmodal List<User>. You should get a better understanding from this fiddle
readHttpResponse can be
{
"msg": null,
"data": [{
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
}],
"error": false
}
and
readHttpResponse.data needs to be array
[{
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
}]

Convert Json property based on property value

I would like to deserialize a json to object. The json is like below. But one property value maybe string or array, does anyone know how to handle this?
{
"name": "123", //Name
"properties": [
{
"propertyId": "Subject", // property id
"value": [
{
"entityId": "math", //entity id
"entityTypeId": "MATH" //entity type id
}
]
},
{
"propertyId": "Description",
"value": "Hello World."
}
]
}
The class is like below.
//The object
public class Content
{
public Content()
{
//Properties is List.
Properties = new List<Property>();
}
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "properties")]
public List<Property> Properties { get; set; }
}
public class Property
{
public Property()
{
Value = new List<Value>();
}
[JsonProperty(PropertyName = "propertyId")]
public string PropertyDefId { get; set; }
//Actually this property value can also be string, that's the problem.
[JsonProperty(PropertyName = "value")]
public List<Value> Value { get; set; }
}
//Value object
public class Value
{
//Have to write comments.
[JsonProperty(PropertyName = "entityId")]
public string EntityId { get; set; }
//Have to write comments.
[JsonProperty(PropertyName = "entityTypeId")]
public string EntityTypeId { get; set; }
}
I've done this in Java with Gson liblary and it was like
JsonObject field = parser.parse(json).getElementAsJSONObject();
if (field.isPrimitive()) {
String text = field.asString();
} else if (field.isArray()) {
JSONArray array = field.asArray();
}
I wrote this code from my memory so not 100% reliable. I don't know any solution for C# though.
$.parseJSON will convert your string to the correct object even if the property type is different for two different properties.
http://jsfiddle.net/mdanielc/e0acsyp1/2/
var jsonString = '{"name": "123","properties": [{"propertyId": "Subject","value": [{"entityId":"math","entityTypeId": "MATH" }]},{"propertyId": "Description","value": "Hello World."}]}';
var jsonobj = $.parseJSON(jsonString);
alert(jsonobj.properties[0].value[0].entityId);
alert(jsonobj.properties[1].value);
});

Categories