CodexBloom - Programming Q&A Platform

How to implement guide with using `serde_json` to deserialize a nested json structure into rust structs with optional fields

👀 Views: 9083 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-01
rust serde serde-json Rust

I'm integrating two systems and I'm updating my dependencies and I'm upgrading from an older version and I'm relatively new to this, so bear with me..... Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to deserialize a nested JSON structure into Rust structs using `serde_json`, but I'm running into issues when the optional fields are not present in the input JSON. My JSON looks like this: ```json { "user": { "id": 1, "name": "John Doe", "profile": { "age": 30, "bio": null } } } ``` I have defined my structs like this: ```rust use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] struct Profile { age: u32, bio: Option<String>, } #[derive(Serialize, Deserialize, Debug)] struct User { id: u32, name: String, profile: Option<Profile>, } #[derive(Serialize, Deserialize, Debug)] struct Response { user: User, } ``` I expected that when `profile` is missing from the JSON, the `profile` field in my `User` struct would simply be `None`. However, I'm getting a `serde_json::behavior` with the message: `missing field `profile` at line 1 column 92`. I've tried marking the `profile` field in the `User` struct as optional, but it doesn't seem to have any effect. I confirmed that I have the latest version of `serde` (1.0.130) and `serde_json` (1.0.66) in my `Cargo.toml`. What am I missing here? How can I make the deserialization work correctly with optional nested fields in this scenario? For context: I'm using Rust on Linux. I'd really appreciate any guidance on this. My team is using Rust for this mobile app. What's the correct way to implement this? I'm working with Rust in a Docker container on Ubuntu 20.04. Any help would be greatly appreciated! My development environment is CentOS. How would you solve this? This is happening in both development and production on Windows 10. Am I missing something obvious?