Deserializing weirdly formatted JSON to an object in C#

Kim Karlsson

I'm trying to teach myself working with APIs, and chose to try and make something that fetches currency exchange rates from a certain free API regarding just that. I've managed to successfully make the API call and record the JSON data from it, and I'd like to save the data so it's easily accessible from an object.

My issue is this; the JSON data reads like

{
    "Realtime Currency Exchange Rate": {
        "1. From_Currency Code": "USD",
        "2. From_Currency Name": "United States Dollar",
        "3. To_Currency Code": "EUR",
        "4. To_Currency Name": "Euro",
        "5. Exchange Rate": "0.87490000",
        "6. Last Refreshed": "2020-07-19 08:16:36",
        "7. Time Zone": "UTC",
        "8. Bid Price": "0.87490000",
        "9. Ask Price": "0.87540000"
    }
}

Using https://json2csharp.com/ I'm getting a result like this

public class RealtimeCurrencyExchangeRate    {
    public string 1.From_CurrencyCode { get; set; } 
    public string 2.From_CurrencyName { get; set; } 
    public string 3.To_CurrencyCode { get; set; } 
    public string 4.To_CurrencyName { get; set; } 
    public string 5.ExchangeRate { get; set; } 
    public string 6.LastRefreshed { get; set; } 
    public string 7.TimeZone { get; set; } 
    public string 8.BidPrice { get; set; } 
    public string 9.AskPrice { get; set; } 
}

Which isn't valid c# syntax. The JSON parser I have could deserialize that info (I think) but Visual Studio is throwing a well deserved fit over me trying to name a variable 1.From_CurrencyCode

haldo

You can use the JsonProperty attribute (if you're using Newtonsoft.Json) to decorate each of your model properties. This allows you to rename the Json property names to valid C# property names.

public class RealtimeCurrencyExchangeRate    
{
    [JsonProperty("1. From_Currency Code")]
    public string FromCurrencyCode { get; set; } 
    
    // similarly for the remaining properties
    ...
}

// also apply it to your "root" class
public class Root    
{
    [JsonProperty("Realtime Currency Exchange Rate")]
    public RealtimeCurrencyExchangeRate RealtimeCurrencyExchangeRate { get; set; }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Problems Deserializing Nested JSON Array in C#

분류에서Dev

Update a JSON formatted JavaScript object based on another

분류에서Dev

JSon.NET deserializing object doesn't work

분류에서Dev

Deserializing Xml string into object with List<>

분류에서Dev

DeSerializing JSON은 null C #을 반환합니다.

분류에서Dev

Json Formatted with Square Brackets

분류에서Dev

Deserializing JSON with odd structure with JSON.NET

분류에서Dev

JSON.NET: Deserializing from JSON with LINQ

분류에서Dev

Java SerialIzation: 'ClassNotFoundException' when deserializing an Object

분류에서Dev

newtonsoft json deserializing 문제 (충돌)

분류에서Dev

Deserializing a jagged array via JSON.NET with types

분류에서Dev

Iterate through json object in c#

분류에서Dev

Japanese displays weirdly in chrome

분류에서Dev

Convert a Bibtex class object to a series of text strings formatted for each citation

분류에서Dev

Force Chrome to show Json response formatted as tree structure

분류에서Dev

Parse JSON response with multiple datetime formats to c# object

분류에서Dev

복잡한 Json to C # Object Deserialize with classes

분류에서Dev

JSON serialize a custom C# struct to a string, not an Object

분류에서Dev

JSon.NET deserializing 개체가 작동하지 않습니다.

분류에서Dev

Json.NET deserializing 개체는 항상 null을 표시합니다.

분류에서Dev

C++ Hazelcast with Protobuf serialization: String is not UTF-8 formatted

분류에서Dev

How does C interpret data from a union if it's formatted differently?

분류에서Dev

Accessing JSON object in Handlebars [object Object] error

분류에서Dev

Deserializing Option은 json4s에서 예외 대신 None을 반환합니다.

분류에서Dev

웹 API 포스트 deserializing json 결과이지만 모든 속성은 null

분류에서Dev

Google지도 API json에서 formatted_address 가져 오기

분류에서Dev

Get formatted data in shell script which is read from file containing JSON data

분류에서Dev

Reordering data in JSON Object

분류에서Dev

Return JSON object problems

Related 관련 기사

  1. 1

    Problems Deserializing Nested JSON Array in C#

  2. 2

    Update a JSON formatted JavaScript object based on another

  3. 3

    JSon.NET deserializing object doesn't work

  4. 4

    Deserializing Xml string into object with List<>

  5. 5

    DeSerializing JSON은 null C #을 반환합니다.

  6. 6

    Json Formatted with Square Brackets

  7. 7

    Deserializing JSON with odd structure with JSON.NET

  8. 8

    JSON.NET: Deserializing from JSON with LINQ

  9. 9

    Java SerialIzation: 'ClassNotFoundException' when deserializing an Object

  10. 10

    newtonsoft json deserializing 문제 (충돌)

  11. 11

    Deserializing a jagged array via JSON.NET with types

  12. 12

    Iterate through json object in c#

  13. 13

    Japanese displays weirdly in chrome

  14. 14

    Convert a Bibtex class object to a series of text strings formatted for each citation

  15. 15

    Force Chrome to show Json response formatted as tree structure

  16. 16

    Parse JSON response with multiple datetime formats to c# object

  17. 17

    복잡한 Json to C # Object Deserialize with classes

  18. 18

    JSON serialize a custom C# struct to a string, not an Object

  19. 19

    JSon.NET deserializing 개체가 작동하지 않습니다.

  20. 20

    Json.NET deserializing 개체는 항상 null을 표시합니다.

  21. 21

    C++ Hazelcast with Protobuf serialization: String is not UTF-8 formatted

  22. 22

    How does C interpret data from a union if it's formatted differently?

  23. 23

    Accessing JSON object in Handlebars [object Object] error

  24. 24

    Deserializing Option은 json4s에서 예외 대신 None을 반환합니다.

  25. 25

    웹 API 포스트 deserializing json 결과이지만 모든 속성은 null

  26. 26

    Google지도 API json에서 formatted_address 가져 오기

  27. 27

    Get formatted data in shell script which is read from file containing JSON data

  28. 28

    Reordering data in JSON Object

  29. 29

    Return JSON object problems

뜨겁다태그

보관