Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Turn array of values without keys into object #959

Closed
adrianbrink opened this issue Jun 18, 2017 · 1 comment
Closed

Turn array of values without keys into object #959

adrianbrink opened this issue Jun 18, 2017 · 1 comment
Labels

Comments

@adrianbrink
Copy link

Hi,

I receive this JSON over the wire: [1,[2556,2.06,2559.5,4.8,18.4,0.0073,2556,22039.67029419,2640,2450.1]]

and I would like to decode it into a struct like this:

pub struct Example {
    value_one: 1
    value_two: 2556
    value_three: 2.06
    ...
}

Does serde-rs implement this out of the box? Please note that none of the values in the array come with a key. I only have the values.

@dtolnay
Copy link
Member

dtolnay commented Jun 18, 2017

Decoding JSON arrays into a struct is supported out of the box. You will need to combine them if you want two arrays to deserialize into one struct.

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

#[derive(Deserialize, Debug)]
struct Outer {
    value_one: u64,
    inner: Inner,
}

#[derive(Deserialize, Debug)]
struct Inner {
    value_two: u64,
    value_three: f64,
    value_four: f64,
    value_five: f64,
    value_six: f64,
    value_seven: f64,
    value_eight: u64,
    value_nine: f64,
    value_ten: u64,
    value_eleven: f64,
}

fn main() {
    let j = "[1,[2556,2.06,2559.5,4.8,18.4,0.0073,2556,22039.67029419,2640,2450.1]]";
    let s: Outer = serde_json::from_str(j).unwrap();
    println!("{:#?}", s);
}

@dtolnay dtolnay closed this as completed Jul 21, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants