I have a problem. I am trying to parse my json to 2 classes. Here is the json:
{
"user":[
[
{
"Id":"0",
"Username":"Vreeswijk",
"ProfilePicture":"media/user/0.png"
}
]
],
"token":[
[
{
"access_token":"myToken1",
"refresh_token":"myToken2",
"expires_in":3600,
"expires_on":1577363756
}
]
]
}
And here are my 2 classes:
public class Token
{
public string access_token { get; set; }
public string refresh_token { get; set; }
public int expire_in { get; set; }
public int expire_on { get; set; }
public Token() { }
}
And here is the user class:
public class User
{
[PrimaryKey]
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ProfilePicture { get; set; }
public User() { }
public User(string Username, string Password)
{
this.Username = Username;
this.Password = Password;
}
}
Now I want to deserialize the json to those 2 classes.
Here is my code now that works for 1 class only:
var jObject = JObject.Parse(json);
var userPropery = jObject["user"] as JArray;
userList= new List<user>();
foreach (var property in userPropery )
{
var propertyList = JsonConvert.DeserializeObject<List<user>>(property.ToString());
userList.AddRange(propertyList);
}
How can I make this work for 2 classes in 1 json?
If you observe your Json, both user and token are nested Arrays. You can now create Root Class that has both the required properties. For Example
public class Root
{
public List<List<User>> user { get; set; }
public List<List<Token>> token { get; set; }
}
Now, instead of using JObject.Parse you could deserialize it directly as
var root = JsonConvert.DeserializeObject<Root>(json);
To get a flattened user and token list, you can use
var userList= root.user.SelectMany(x=>x);
var tokenList= root.token.SelectMany(x=>x);
You can create a Root class for your json and add two properties in it with User and Token classes as required.
public class Root
{
public List<List<User>> Users { get; set; }
public List<List<Token>> Tokens { get; set; }
}
Then pass this class in DeserializeObject function to deserialize the json.
Why don't you create a class include both user and token?
If you don't do this, please parse one by one.
Related
I'm querying an external service and wanted to deserialize the response into a customer object but the issue is response for each customer may be different. some customer may have Sales entity in the response and few may have Marketing.
The json property for sales entity is SalesId and for marketing is MarketingId. Can you advise whether the model I use to store result is correct or any improvement ? If so, how would I deserialize the response without knowing the correct json property ?
For Customer 66666
{
"customerId": "66666",
"customerName": "test1234",
"dependentEntity": [
{
"SalesId": "3433434",
"SalesPersonName": "343434",
"SaleSource": "StorePurchase"
}
]
}
For Customer 5555
{
"customerId": "55555",
"customerName": "test2",
"dependentEntity": [
{
"MarketingId": "3433434",
"MarketingAppName": "343434",
"MarketingSource": "Online"
}
]
}
Here is the Model I'm thinking but not sure the correct one
public class Customer
{
public string customerId { get; set; }
public string customerName { get; set; }
public IList<T> dependentList { get; set; }
}
public class Dependent
{
[JsonProperty("Id")]
public string Id { get; set; }
public string Name { get; set; }
public string Source { get; set; }
}
You could probably try something like the following one:
public class DependentEntity
{
[JsonProperty("SalesId")]
public string SalesId { get; set; }
[JsonProperty("SalesPersonName")]
public string SalesPersonName { get; set; }
[JsonProperty("SaleSource")]
public string SaleSource { get; set; }
[JsonProperty("MarketingId")]
public string MarketingId { get; set; }
[JsonProperty("MarketingAppName")]
public string MarketingAppName { get; set; }
[JsonProperty("MarketingSource")]
public string MarketingSource { get; set; }
}
public class Customer
{
[JsonProperty("customerId")]
public string CustomerId { get; set; }
[JsonProperty("customerName")]
public string CustomerName { get; set; }
[JsonProperty("dependentEntity")]
public IList<DependentEntity> DependentEntity { get; set; }
}
We have a type for DependentEntity that has both the attributes of Marketing and Sales object. After parsing your input, you could create a logic (checking the attributes) based on which you could check if a DependentEntity is a Marketing or a Sales object.
The above classes was generated using, jsonutils.
If we can assume that the dependentEntity contains only a single type of objects then you can use json.net's schema to perform branching based on the matching schema.
So, lets suppose you have these dependent entity definitions:
public class DependentMarket
{
public string MarketingId { get; set; }
public string MarketingAppName { get; set; }
public string MarketingSource { get; set; }
}
public class DependentSales
{
public string SalesId { get; set; }
public string SalesPersonName { get; set; }
[JsonProperty("SaleSource")]
public string SalesSource { get; set; }
}
...
Then you can use these classes to generate json schemas dynamically:
private static JSchema marketSchema;
private static JSchema salesSchema;
//...
var generator = new JSchemaGenerator();
marketSchema = generator.Generate(typeof(DependentMarket));
salesSchema = generator.Generate(typeof(DependentSales));
And finally you can do the branching like this:
var json = "...";
var semiParsedJson = JObject.Parse(json);
JArray dependentEntities = (JArray)semiParsedJson["dependentEntity"];
JObject probeEntity = (JObject)dependentEntities.First();
if (probeEntity.IsValid(marketSchema))
{
var marketEntities = dependentEntities.ToObject<List<DependentMarket>>();
...
}
else if (probeEntity.IsValid(salesSchema))
{
var salesEntities = dependentEntities.ToObject<List<DependentSales>>();
...
}
else if ...
else
{
throw new NotSupportedException("The provided json format is not supported");
}
I have json that looks like this, the key "123" could be any number.
{
"key1": "",
"key2": {
"items": {
"123": {
"pageid": 123,
"name": "data"
}
}
}
}
I want to deserialize or query the json with System.Text.Json so i can get the value of the key "name". How can I do that with System.Text.Json? I'm using .NET Core 3.1.
Since one of the json keys can vary ("123"), this can be represented by a Dictionary<>. The following classes model your json.
public class ItemProps
{
public int pageid { get; set; }
public string name { get; set; }
}
public class Item
{
public Dictionary<string, ItemProps> items { get; set; }
}
public class Root
{
public string key1 { get; set; }
public Item key2 { get; set; }
}
Then to deserialize using System.Text.Json you would use:
var data = JsonSerializer.Deserialize<Root>(json);
To access name:
var name = data.key2.items["123"].name
Try it online
Note, I named the classes quickly... please consider giving the classes better names, more descriptive names.
Something like:
public class Rootobject
{
public string key1 { get; set; }
public InnerObject key2 { get; set; }
}
public class InnerObject
{
public Dictionary<string, ObjectTheThird> items { get; set; }
= new Dictionary<string, ObjectTheThird>();
}
public class ObjectTheThird
{
public int pageid { get; set; }
public string name { get; set; }
}
and use the APIs on Dictionary<,> to look at the items. Or you just want the first:
var name = obj.key2.items.First().Value.name;
If my string(json) contain only following part, I am able to deserialize it with the help of newtonsoft's library.
{"Code": "MXXXXX", "Status": "failed"}
Code to deserialize:
public class Account
{
public string Code{ get; set; }
public string Status{ get; set; }
}
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Code);
But if my string is like this:
{'data': ' {"Code": "MXXXXX", "Status": "failed"}'}
I am unable to deserialize. Here the class has only one property which is data... how can I do that?
You will need another class for that which wraps the actual account , like:
public class Account
{
public Data Data { get; set };
}
public class Data
{
public string Code{ get; set; }
public string Status{ get; set; }
}
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account .Data.Code);
Try this
public class Account
{
public string Code { get; set; }
public string Status { get; set; }
}
public class AccountWrapper
{
[JsonProperty(PropertyName = "data")]
public string Data { get; set; }
public Account Account
{
get { return JsonConvert.DeserializeObject<Account>(Data); }
}
}
// DeserializeObject
string data = "{'data':'{\"Code\":\"MXXXXX\",\"Status\":\"failed\"}'}";
var account = JsonConvert.DeserializeObject<AccountWrapper>(data).Account;
You could deserialize the whole json as JObject, and then parse part of it into Account:
JObject wholeJson = JObject.Parse(json);
JToken dataToken = wholeJson.GetValue("data");
Account account = dataToken.ToObject<Account>();
My suggestion is that, You can prepare the same object as of the json structure. Like,
public class Test
{
public string data{ get; set; }
}
you can get data out of the object and deserialize it as your doing it now.
Or read it in JObject and then get the data and deserialize it.
I want to parse a piece of JSON with Newtonsoft Json.NET
JSON:
{
"USER":{
"result_id":"0",
"result_description":"NET Connections",
"cmlog_username":[
"8118236834",
"8118236834",
"8118236834"
],
"caller_id":[
"14cc20f7b05f",
"14cc20f7b05f",
"14cc20f7b05f"
]
}
}
Class
public class USER
{
public string result_id;
public string result_description;
public string[] cmlog_username;
public string[] caller_id;
}//USER
I convert it with below code but all of property value is NULL
USER con = JsonConvert.DeserializeObject<USER>(msg);
Your deserialization class is incorrect. Putting your JSON into json2csharp.com produces:
public class USER
{
public string result_id { get; set; }
public string result_description { get; set; }
public List<string> cmlog_username { get; set; }
public List<string> caller_id { get; set; }
}
public class RootObject
{
public USER USER { get; set; }
}
So you would need to do:
User con = JsonConvert.DeserializeObject<RootObject>(msg);
Your JSON object isn't a USER, it's an object that contains a USER.
It's because the JSON object you are trying to parse into a user is an object that has a property of 'user' that is a user object. That probably didn't make much sense. You could change your json to be
{
"result_id":"0",
"result_description":"NET Connections",
"cmlog_username":[
"8118236834",
"8118236834",
"8118236834"
],
"caller_id":[
"14cc20f7b05f",
"14cc20f7b05f",
"14cc20f7b05f"
]
}
and it will work.
Try adding the get and set to your class
public class USER
{
public string result_id { get; set; }
public string result_description { get; set; }
public string[] cmlog_username { get; set; }
public string[] caller_id { get; set; }
}//USER
My Goal:
Read JSON from site, get values of certain items and display them, after I successfully
pull that off I will want to implement taking in a value like true and set it to false.
For starters I need help figuring out how to read and write the variables. I have read
lots of tutorials and blogs about how to read in the data and parse it but what isn't
explained is where is the value stored?
Like I have this http://elsite.com/.json and it has this:
{
dola: "p9", data:{
house: [{
dola: "p9", data:{
owner: "blah", // string
price: blah, // int
url: "http://www.link.com", // url/string
message: "blahblah",
checked: false
}
},
{
dola: "p9", data:{
owner: "blah", // same as above
I have built this to get the data:
[DataContract]
class container
{
[DataMember(Name = "data")]
public Data1 dataStart { get; set; }
[DataContract]
public class Data1
{
[DataMember(Name = "house")]
public HouseA[] home { get; set; }
[DataContract]
public class HouseA
{
[DataMember(Name = "data")]
public Data2 dataSec { get; set; }
[DataContract]
public class Data2
{
[DataMember(Name = "owner")]
public string own { get; set }
[DataMember(Name = "message")]
public strinng mess { get; set; }
}
}
}
}
I want to use
var blah = from post in container.dataStart.house.data // obviously not the right way to do it
select new MessageItem
{
User = post.own,
Meza = post.mess
}
with
public class MessageItem
{
public string User;
public string Meza;
}
So basically it boils down to I am not COMPLETELY understanding the structure of the arrays and objects.
Anyone able to guide me in the right way to do the from.in.select?
Have you looked at Json.NET http://json.codeplex.com/ which includes LINQ to JSON support
I prefer JavaScriptSerializer (System.Web.Extensions.dll) for this; the following works:
JsonResult obj = new JavaScriptSerializer().Deserialize<JsonResult>(json);
var qry = from house in obj.data.house
let post = house.data
select new MessageItem
{
User = post.owner,
Meza = post.message
};
with:
class JsonResult
{
public string dola { get; set; }
public Data data { get; set; }
public class Data
{
public List<House> house { get; set; }
}
public class House
{
public string dola { get; set; }
public HouseData data { get; set; }
}
public class HouseData
{
public string owner { get; set; }
public int price {get;set;}
public Uri url {get;set;}
public string message {get;set;}
public bool #checked {get;set;}
}
}