[英]How to convert two json properties that have same name into properties in same class
I have a json object: 我有一个JSON对象:
{
"user": {
"id": "xxx"
},
"session": {
"id": "xxx"
}
}
now I need to convert json into a class, 现在我需要将json转换为类,
my default answer is to write properties as UserID,sessionID 我的默认答案是将属性写为UserID,sessionID
but I wish something like User.ID & session.ID(which is not possible) from readability point of view. 但是从可读性的角度来看,我希望像User.ID和session.ID这样的东西(不可能)。
Make a base class: 创建一个基类:
public class BaseId //Come up with a better name
{
public string Id { get; set; }
}
Then inherit it from these classes: 然后从这些类继承它:
public class User : BaseId
{
//Other stuff if you want
}
public class Session : BaseId
{
//Other stuff if you want
}
However you should only do this if User and Session have unique differences from one another (but obviously share the ID property). 但是,只有在User和Session彼此具有唯一差异(但显然共享ID属性)的情况下,才应执行此操作。
If you just want two different variables, then parse them into two different instances of the BaseId class named user
and session
(obviously no need for the concrete classes this way) 如果只需要两个不同的变量,则将它们解析为名为user
和session
的BaseId类的两个不同实例(显然,不需要这种具体的类)
You can use JsonProperty
class of Newtonsoft.Json
您可以使用Newtonsoft.Json
JsonProperty
类
public class Model
{
[JsonProperty(PropertyName = "UserId")]
public int ID { get; set; }
[JsonProperty(PropertyName = "SessionId")]
public int ID1 { get; set; }
}
I'm not sure I understand the question entirely. 我不确定我是否完全理解这个问题。 If I were to do this, it would look like this: 如果我要这样做,它将看起来像这样:
public class Foo
{
[JsonProperty("user")]
public User UserIdentity { get; set; }
[JsonProperty("session")]
public Session CurrentSession { get; set; }
}
public class User
{
[JsonProperty("id")]
string Id { get; set; }
}
public class Session
{
[JsonProperty("id")]
string Id { get; set; }
}
public class User
{
[JsonProperty("id")]
public string id { get; set; }
}
public class Session
{
[JsonProperty("id")]
public string id { get; set; }
}
public class MyJson
{
[JsonProperty("user")]
private User user { get; set; }
[JsonProperty("session")]
private Session session { get; set; }
public string UserID { get { return user.id; } }
public string SessionID { get { return session.id; } }
}
You Can Write the Model of This type, You can Get the Data As You Request Type of UserID and SessionID. 您可以编写这种类型的模型,您可以根据请求的UserID和SessionID类型获取数据。
In Below Sample Code For Testting 在下面的示例代码中进行测试
var teststring = JsonConvert.DeserializeObject<JObject>("{\"user\": {\"id\": \"xxx\"},\"session\": {\"id\": \"xxx\"}");
var data = JsonConvert.DeserializeObject<MyJson>(teststring.ToString());
var session = data.SessionID;
var userId = data.UserID;
I Was Checked Properly. 我被正确检查了。 It Working fine. 工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.