简体   繁体   English

反序列化 json 文件时 Serde 缺少字段错误

[英]Serde missing field error when deserializing json file

I can't seem to grasp why this error is happening.我似乎无法理解为什么会发生这个错误。

Am I following the docs wrong?我是否按照文档错误?

This is the error I am getting and it happens with all the fields in the struct except the map:这是我得到的错误,除了 map 之外,结构中的所有字段都会发生这种情况:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("missing field `link`", line: 10, column: 1)', src\main.rs:22:47

This is my main.rs这是我的main.rs

use serde_json::{self, Value};
use std::{fs, collections::HashMap};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Init {
    link: String,
    page: String,
    pageid: u16,
    update_timestamp: u16,

    #[serde(flatten)]
    char_page_info: HashMap<String, Value>
}

fn main() {
    let data = fs::read_to_string("init.json").expect("Unable to read file");
    println!("{}", data);
    let p: Init = serde_json::from_str(&data).unwrap();
    println!("{:#?}", p.char_page_info); 
}

This is the init.json这是init.json

{
    "char_page_info": [
        {
            "link": "",
            "page": "GGST/Jack-O/Frame_Data",
            "pageid": 27121,
            "update_timestamp": 0
        }
    ]
}

If i remove link: String, page: String, pageid: u16, update_timestamp: u16,如果我删除link: String, page: String, pageid: u16, update_timestamp: u16,

it doesn't throw any errors and deserializes without any hiccups.它不会抛出任何错误并且反序列化没有任何问题。

Can someone explain to me why that is?有人可以向我解释为什么会这样吗?

It's not just link that is missing: Serde bails at the first error.丢失的不仅仅是link :Serde 在第一个错误时就放弃了。 link , page , and pageid , and update_timestamp are all missing. linkpagepageid以及update_timestamp都丢失了。 Serde looks for those fields on the top level object, and doesn't find them, since the only key present there is char_page_info . Serde 在顶层 object 上查找这些字段,但没有找到它们,因为那里唯一的键是char_page_info Since there can be multiple values of char_page_info (it is an array), your struct doesn't model the underlying data correctly.由于char_page_info可以有多个值(它是一个数组),因此您的struct不会正确地 model 基础数据。 By fully modelling the data, we can get the expected results:通过对数据进行充分建模,我们可以得到预期的结果:

#[derive(Serialize, Deserialize, Debug)]
struct Init {
    link: String,
    page: String,
    pageid: u16,
    update_timestamp: u16,
}

#[derive(Serialize, Deserialize, Debug)]
struct Data {
    char_page_info: Vec<Init>,
}

let data = r#"{
    "char_page_info": [
        {
            "link": "",
            "page": "GGST/Jack-O/Frame_Data",
            "pageid": 27121,
            "update_timestamp": 0
        }
    ]
}"#;
println!("{}", data);
let p: Data = serde_json::from_str(&data).unwrap();
println!("{:#?}", p.char_page_info); 

(playground) (操场)

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

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