0
{
     "odata.metadata": "sometext",
     "odata.nextLink": "sometext",
    "value": [{
            "odata.type": "SP.Data.RegionsListItem",
            "odata.id": "07404daa-61b5-4947-af9f-38f29822f775",
            "odata.etag": "\"3\"",
            "odata.editLink": "Web/Lists(guid'65dc896b-df87-4145-98d9-57c7ea619e66')/Items(3)",
            "FileSystemObjectType": 0,
            "Id": 3,
            "ServerRedirectedEmbedUri": null,
             }]
    
}

this is an example of my Json string i cant change its key names any sugestion? thanks in advance.

someone
  • 139
  • 1
  • 12
  • 1
    What library are you using for deserialization? – Guru Stron Apr 19 '21 at 13:22
  • Does this answer your question? [RestSharp - deserialize json response with invalid key name (contains a period )](https://stackoverflow.com/questions/33009218/restsharp-deserialize-json-response-with-invalid-key-name-contains-a-period) also check out https://stackoverflow.com/questions/36376524/accessing-properties-with-a-dot-in-their-name/47402430#47402430 – Trevor Apr 19 '21 at 13:27

2 Answers2

6

Depending on the library you are using for deserialization you can mark model fields with corresponding attributes - for example JsonPropertyNameAttribute for System.Text.Json or JsonPropertyAttribute for Newtonsoft.Json.

Newtonsoft.Json:

public class Root
{
    [JsonProperty("odata.metadata")]
    public string OdataMetadata { get; set; }

    [JsonProperty("odata.nextLink")]
    public string OdataNextLink { get; set; }

    [JsonProperty("value")]
    public List<Value> Value { get; set; } // do the same for Value type
}

 var result = JsonConvert.DeserializeObject<Root>(json);

System.Text.Json:

public class Root
{
    [JsonPropertyName("odata.metadata")]
    public string OdataMetadata { get; set; }

    [JsonPropertyName("odata.nextLink")]
    public string OdataNextLink { get; set; }

    [JsonPropertyName("value")]
    public List<Value> Value { get; set; }
}


var result = JsonSerializer.Deserialize<Root>(json);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
2

When you create a class for your data, you can use annotations for the class members. For instance when using Newtonsoft.Json it works this way:

class MyData {

[JsonProperty("odata.metadata")]
public string Metadata {get;set;}

[JsonProperty("odata.nextlink")]
public string NextLink {get;set;}

... 
}

With other libraries, the annotations may be named differently. Also make sure, you are importing the correct namespace and use the correct annotations for the library you are using. Ie for instance the System.Text.Json.JsonPropertyName annotation won't have any effect, when deserializing with Newtonsoft.Json and vice versa.

Then you can deserialize

var data = JsonConvert.DeserializeObject<MyData>(thejsonstring);

and access the property with its .NET name

 var metadata = data.Metadata;
derpirscher
  • 14,418
  • 3
  • 18
  • 35