Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust & Serde JSON deserialization examples?

Tags:

I'm trying to figure out how to deserialize JSON into a structure using Serde. For instance, the example JSON on serde_json's own documentation contains the following data:

{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "PhoneNumbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}

Now, if we assume that the above data is in a variable "input" and the following piece of code:

let deserialized_data: Data = serde_json::from_str(input).unwrap();

... what should struct Data look like?

like image 486
vegai Avatar asked Oct 21 '15 05:10

vegai


People also ask

Is Rust free to play?

No, Rust is not a free game. It is a paid experience without any free-to-play game modes. The game is currently available for purchase on Steam for a listed price of $39.99.

Is Rust better than C++?

Rust is syntactically similar to C++, but it provides increased speed and better memory safety. Rust is a more innovative system-level language in terms of safer memory management because it does not allow dangling pointers or null pointers.

What is Rust is used for?

Rust is a low-level programming language with direct access to hardware and memory, which makes it a great solution for embedded and bare-metal development. You can use Rust to write operation systems or microcontroller applications.

Is Rust better than Python?

One major reason why Rust is overtaking Python is performance. Because Rust is compiled directly into machine code, there is no virtual machine or interpreter sitting between your code and computer. Another key advantage over Python is Rust's thread and memory management.


1 Answers

Most of the standard data structures are serializable, so the following structures should work:

#[derive(Serialize, Deserialize)]
struct Data {
    FirstName: String,
    LastName: String,
    Age: u32,
    Address: Address,
    PhoneNumbers: Vec<String>
}

#[derive(Serialize, Deserialize)]
struct Address {
    Street: String,
    City: String,
    Country: String
}

If some of the fields in input may be absent, then the corresponding structure fields should be Option<T> instead of just T.

Note that it is possible to name fields in a more "Rusty" manner, i.e. snake_case, because serde supports renaming annotations:

#[derive(Serialize, Deserialize)]
struct Address {
    #[serde(rename="Street")]
    street: String,
    #[serde(rename="City")]
    city: String,
    #[serde(rename="Country")]
    country: String
}

This issue is also relevant to fields renaming.

like image 97
Vladimir Matveev Avatar answered Oct 14 '22 22:10

Vladimir Matveev