Reputation: 31
I have two JSON files. One which contains info about a player and the other about his team.
I deserialized the team JSON file in C# and made a team object. In the player class, there is a property 'teamassigned' in which I want the value to be the team object I made earlier, but I want to store it in a JSON file.
JSON For Driver
{
"driverName": "Esyltt Aviars",
"teamAssigned": TEAM OBJECT HERE,
"DefendingScore": 47,
"BrakingScore": 80,
"CorneringScore": 38,
"RaceStartScore": 92,
"ConsistencyScore": 74,
"FocusScore": 55
}
JSON For Team
{
"teamID": 1,
"teamName": "Mclaren",
"teamColor": "orange"
}
Upvotes: 2
Views: 100
Reputation: 1033
You can achieve this in following way:
Your Classes for Player & Team will be:
public class Team
{
public int teamID { get; set; }
public string teamName { get; set; }
public string teamColor { get; set; }
}
public class Player
{
public string driverName { get; set; }
public Team teamAssigned { get; set; }
public int DefendingScore { get; set; }
public int BrakingScore { get; set; }
public int CorneringScore { get; set; }
public int RaceStartScore { get; set; }
public int ConsistencyScore { get; set; }
public int FocusScore { get; set; }
}
When deserialize the data of these classes, the resultant Json would be:
{
"driverName": "Esyltt Aviars",
"team": {
"teamID": 1,
"teamName": "Mclaren",
"teamColor": "orange"
},
"DefendingScore": 47,
"BrakingScore": 80,
"CorneringScore": 38,
"RaceStartScore": 92,
"ConsistencyScore": 74,
"FocusScore": 55
}
Updated Answer As Required
Above two classes Player and Team are used to deserialize Json data to objects, as given below:
var objPlayer = JsonConvert.DeserializeObject<Player>(playerJson);
var objTeam = JsonConvert.DeserializeObject<Team>(teamJson);
As a result got data in two objects. Now assign both objects data to a new object of type Player along with assign values of object Team to the field "teamAssigned", as given below:
var objMerged = new Player()
{
driverName = objPlayer.driverName,
teamAssigned = new Team()
{
teamID = objTeam.teamID,
teamName = objTeam.teamName,
teamColor = objTeam.teamColor
},
DefendingScore = objPlayer.DefendingScore,
BrakingScore = objPlayer.BrakingScore,
CorneringScore = objPlayer.CorneringScore,
RaceStartScore = objPlayer.RaceStartScore,
ConsistencyScore = objPlayer.ConsistencyScore,
FocusScore = objPlayer.FocusScore,
};
Now, serialze this object "objMerged" to Json as:
var convertToJson = JsonConvert.SerializeObject(objMerged);
The resultant Json in "convertToJson" will be as per requirement with property 'teamassigned' having the value to be the team object.
Upvotes: 2