Struct with sections to organize the data.

huangapple go评论61阅读模式
英文:

Struct with sections to organize the data

问题

To organize and use the JSON data in your Rust code as you've described, you can create a struct for each section you want to represent and then include them in a new struct. Here's how you can structure your Rust code:

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Section1 {
    pub brand: String,
    pub price: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Section2 {
    pub title: String,
    pub description: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MainStruct {
    pub section1: Section1,
    pub section2: Section2,
}

fn main() {
    // Deserialize the JSON data into your MainStruct
    let json_data = r#"
    {
        "section1": {
            "brand": "something",
            "price": "whatever"
        },
        "section2": {
            "title": "here",
            "description": "many"
        }
    }
    "#;

    let main_struct: MainStruct = serde_json::from_str(json_data).unwrap();

    // Access the data as needed
    println!("Brand: {}", main_struct.section1.brand);
    println!("Price: {}", main_struct.section1.price);
    println!("Title: {}", main_struct.section2.title);
    println!("Description: {}", main_struct.section2.description);
}

This code defines three structs: Section1, Section2, and MainStruct. MainStruct includes instances of Section1 and Section2, effectively organizing the data as you've shown in your example.

Please make sure to add the necessary dependencies (serde and serde_json) to your Cargo.toml file for this code to work.

英文:

If I have access to an API and get the data back as JSON, how do I organize it and use it in my Rust code? I'm trying to understand how to create a struct with sections. For example, to create a struct like this:

struct mainstruct {
   section1 : {
      brand : "something",
      price : "whatever",
   },
   section2 : {
     title : "here",
     description : "many",         
   },
}

Do I create two impls with the two sections and include them in a new struct?
Do I create two enums and include those enums in a new struct?

I get the data from a dummy API with the following code:

use reqwest::{Client, Error};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Product {
    pub id: i64,
    pub title: String,
    pub description: String,
    pub price: i64,
    pub rating: f64,
    pub stock: i64,
    pub brand: String,
    pub category: String,
    pub thumbnail: String,
    pub images: Vec<String>,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let product: Product = Client::new()
        .get("https://dummyjson.com/products/1")
        .send()
        .await?
        .json()
        .await?;
    println!(">>>>>  Brand is : {:#?}", product.brand);
    Ok(())
}

How can I create a some type of data that organize/present it like this?

info {
  price : Product.price,
  category : Product.category,
},
data {
  title : Product.title,
  description : Product.description,
}

答案1

得分: 1

Rust不支持嵌套的结构定义;如果这是你想要的话,它们需要分开定义:

struct Product {
    info: ProductInfo,
    data: ProductData,
}

struct ProductInfo {
    brand: String,
    price: i64,
    /* ... */
}

struct ProductData {
    title: String,
    description: String,
    /* ... */
}

尽管现在这种结构与API的JSON结构不同。在这种情况下,你可以使用#[serde(flatten)]来聪明地处理(在 playground 上演示)。

但如果这不合适,你可能需要为你的“领域”(在内部使用的内容)和“数据传输”(仅用于与其他内容交互)定义单独的类型,并且可能需要实现From来定义它们之间的转换(在 playground 上演示)。

英文:

Rust doesn't support nested struct definitions; they'll need to be separate if that's what you want:

struct Product {
    info: ProductInfo,
    data: ProductData,
}

struct ProductInfo {
    brand: String,
    price: i64,
    /* ... */
}

struct ProductData {
    title: String,
    description: String,
    /* ... */
}

Though now this structure is different from the JSON structure from the API. In this case you can be clever by using #[serde(flatten)] (demo on the playground).

But if that is not appropriate you may need to have separate type definitions for your "domain" (what you want to use internally) and "data transfer" (only used to interface with something else) and probably implement From to define conversions between each other (demo on the playground).

huangapple
  • 本文由 发表于 2023年5月13日 22:28:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定