Import specific properties from JSON
Karen Payne

Karen Payne @karenpayneoregon

About: Microsoft MVP x 12, Microsoft TechNet author, Code magazine author, developer advocate. Have a passion for driving race cars.

Location:
Oregon, USA
Joined:
Jan 1, 2023

Import specific properties from JSON

Publish Date: Jun 1
10 1

Introduction

Learn how to read a json string with known properties and remove unwanted properties, followed by deserializing to a strongly typed class.

From incoming to desired data type

For this demonstration, the following data is incoming data with an extra property, Age, and two properties, Name and Last, which need to be FirstName and LastName.

[
  {
    "Id": 1,
    "Name": "Mary",
    "Last": "Jones",
    "Age": 22
  },
  {
    "Id": 2,
    "Name": "John",
    "Last": "Burger",
    "Age": 44
  },
  {
    "Id": 3,
    "Name": "Anne",
    "Last": "Adams",
    "Age": 33
  },
  {
    "Id": 4,
    "Name": "Paul",
    "Last": "Smith",
    "Age": 29
  },
  {
    "Id": 5,
    "Name": "Lucy",
    "Last": "Brown",
    "Age": 25
  }
]
Enter fullscreen mode Exit fullscreen mode

The class to import data into.

public class Person
{
    public int Id { get; set; }
    [JsonPropertyName("Name")]
    public string FirstName { get; set; }
    [JsonPropertyName("Last")]
    public string LastName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Aliasing properties

JsonPropertyName is used to alias from property names in json to what is in the class.

Removing unwanted properties

This is a simple process, read in a json file with the correct format followed iterating the array and for each item remove one or more properties. Here only one property is being removed.

var jsonArray = JsonNode.Parse(File.ReadAllText("peopleIncoming.json"))!.AsArray();

foreach (var item in jsonArray)
{
    JsonObject obj = item!.AsObject();
    obj.Remove("Age");
}
Enter fullscreen mode Exit fullscreen mode

Next, place the modified json into a variable and write the json to a file.

var updatedJson = jsonArray.ToJsonString(Indented);

DisplayUpdatedJsonPanel(updatedJson);

Console.WriteLine();

File.WriteAllText("People.json", updatedJson);
Enter fullscreen mode Exit fullscreen mode

Indented definition

public static JsonSerializerOptions Indented => new() { WriteIndented = true };
Enter fullscreen mode Exit fullscreen mode

Deserializing to the Person class

var people = JsonSerializer.Deserialize<Person[]>(updatedJson);
Enter fullscreen mode Exit fullscreen mode

The following screenshot is from a sample project that is included.

Output from sample project

Summary

With the provided instructions, it is easy to import json data into a desired format.

See also

C# System.Text.Json

Source code

Comments 1 total

Add comment