简体   繁体   English

是否可以使用 serde_json 反序列化 JSON 对象的一部分?

[英]Is it possible to deserialize part of a JSON object with serde_json?

Assume following JSON:假设以下 JSON:

{
  "person": {
    "first_name": "Ala",
    "last_name": "Makota"
  }
}

Is it possible to deserialize this object to a struct like following, skipping "person" ?是否可以将此对象反序列化为如下结构,跳过"person"

#[derive(Deserialize)]
struct Person {
  first_name: String,
  last_name: String,
}

It's easy to deserialize the JSON object to a wrapped struct, like this:将 JSON 对象反序列化为包装结构很容易,如下所示:

#[derive(Deserialize)]
struct Object {
  person: Person
}

but in my case, I'm only interested in Person structure.但就我而言,我只对Person结构感兴趣。

EDIT:编辑:

While I'm aware that I could use serde_json 's Value type to operate on JSON almost as on a Map , I'm specifically interested in the possibility of leveraging derive and maybe attributes to achieve my goal.虽然我知道我可以使用serde_jsonValue类型来操作 JSON 几乎就像在Map ,但我特别感兴趣的是利用derive和属性来实现我的目标的可能性。

Thinking the json as a map with a "person" key and a Person value it is possible to deserialize into an HashMap and then retrive the Person value.将 json 视为具有“person”键和Person值的映射,可以反序列化为HashMap ,然后检索Person值。

let person = r#"
{
    "person": {
      "first_name": "Ala",
      "last_name": "Makota"
    }
  }
"#;

let deserialized = serde_json::from_str::<HashMap<&str, Person>>(&person);

The turbo fish ::<HashMap<&str, Person>> is used as a compact way to help the compiler to determine the type of deserialization. turbo fish ::<HashMap<&str, Person>>用作帮助编译器确定反序列化类型的紧凑方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM