简体   繁体   中英

How to convert two json properties that have same name into properties in same class

I have a json object:

{
    "user": {
        "id": "xxx"
    },
    "session": {
        "id": "xxx"
    }
}

now I need to convert json into a class,

my default answer is to write properties as UserID,sessionID

but I wish something like User.ID & session.ID(which is not possible) from readability point of view.

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).

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)

You can use JsonProperty class of Newtonsoft.Json

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM