Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize JSON with a top-level array using Serde?

I have a some JSON data that is returned from a web service. The JSON is a top-level array:

[     {         "data": "value1"     },     {         "data": "value2"     },     {         "data": "value3"     } ] 

Using serde_derive to make structs I can can deserialize the data contained within the array, however, I am unable to get Serde to deserialize the top-level array.

Am I missing something, or can Serde not deserialize top level-arrays?

like image 765
Noskcaj Avatar asked Jun 18 '17 00:06

Noskcaj


People also ask

What is Serde JSON?

The Hive JSON SerDe is commonly used to process JSON data like events. These events are represented as single-line strings of JSON-encoded text separated by a new line. The Hive JSON SerDe does not allow duplicate keys in map or struct key names.

How do I deserialize JSON to an object?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How does rust Serde work?

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically. The Serde ecosystem consists of data structures that know how to serialize and deserialize themselves along with data formats that know how to serialize and deserialize other things.


1 Answers

You can simply use a Vec:

use serde::{Serialize, Deserialize};  #[derive(Serialize, Deserialize, Debug)] struct Foo {     data: String, }  fn main() -> Result<(), serde_json::Error> {     let data = r#"[         {             "data": "value1"         },         {             "data": "value2"         },         {             "data": "value3"         }     ]"#;      let datas: Vec<Foo> = serde_json::from_str(data)?;      for data in datas.iter() {         println!("{:#?}", data);     }      Ok(()) } 

If you wish, you could also use transparent:

#[derive(Serialize, Deserialize, Debug)] #[serde(transparent)] struct Foos {     foos: Vec<Foo>, }  let foos: Foos = serde_json::from_str(data)?; 

This allows to encapsulate your data with your type.

like image 76
Stargateur Avatar answered Sep 27 '22 20:09

Stargateur