【问题标题】:Parsing json partially with serde_json使用 serde_json 部分解析 json
【发布时间】:2022-11-10 14:00:06
【问题描述】:

我在 rust 中使用serde_json,我正在调用一个 api 并得到一个非常大的 json 作为回报。

我的问题是,这是否可以部分反序列化这个 JSON。部分是指 JSON 响应的一些属性,但不是所有属性。

例如,我有这个 JSON:

 Object {
        "age_group": String(""),
        "amazon_product_url": String("https://www.amazon.com/dp/0063221489?tag=NYTBSREV-20"),
        "article_chapter_link": String(""),
        "asterisk": Number(0),
        "author": String("Jared Kushner"),
        "book_image": String("https://storage.googleapis.com/du-prd/books/images/9780063221482.jpg"),
        "book_image_height": Number(500),
        "book_image_width": Number(331),
        "book_review_link": String(""),
        "book_uri": String("nyt://book/e5ec4777-5f2f-5622-9288-9b1d96e8fe1d"),
        "buy_links": Array [
            Object {
                "name": String("Amazon"),
                "url": String("https://www.amazon.com/dp/0063221489?tag=NYTBSREV-20"),
            },
            Object {
                "name": String("Apple Books"),
                "url": String("https://goto.applebooks.apple/9780063221482?at=10lIEQ"),
            },
            Object {
                "name": String("Barnes and Noble"),
                "url": String("https://www.anrdoezrs.net/click-7990613-11819508?url=https%3A%2F%2Fwww.barnesandnoble.com%2Fw%2F%3Fean%3D9780063221482"),
            }
}

那么在这种情况下,是否有可能只捕获 buy_linksamazon_product_url 属性而不介意其他人?

【问题讨论】:

  • 您粘贴的代码不是有效的 json。这是serde_json::Value 的调试输出。

标签: json rust serde


【解决方案1】:

如果您只声明您需要的字段,是的,可以只反序列化数据的子集:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn test(s: &str)
{
    let p: Point = serde_json::from_str(s).unwrap();
    println!("{:?}", p);
}

fn main()
{
    test("{"x":0,"y":3}");
    test("{"x":0,"y":2, "z": 4}");
}

输出:

Point { x: 0, y: 3 }
Point { x: 0, y: 2 }

如您所见,第二个测试中存在的"z" 字段被忽略。

请参阅play.rust-lang.org 示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2014-01-18
    相关资源
    最近更新 更多