Converting nested json to flat structure using serde json


#1
{
	"data" : {
		"name" : {
			"first_name" : "",
			"last_name" : ""
		},
		"info" : {
			"gender" : "Male | Female"
		}
	},
	"user" : {
		"email" : "",
		"password" : ""
	}
}

I am trying to convert the above json into the below structure . But I am not able to figure out how to do it in serde

struct CreateUser { 
    email : Email,
    password : String,
    first_name : String,
    last_name : String,
    gender : Gender
}

#2

The “shape” of your JSON is different than the struct, so it may not be possible to restructure it with just annotations. You could implement your own manual deserialization, but it may be easier to just create 3 structs that model the JSON exactly, and then copy the data to the final struct.


#3

I highly recommend using a 2-step approach: use Serde to read the input plain and then use the conversion protocols Rust gives you to construct your CreateUser out of it. Don’t parse directly into your command structures!

This also give you the ability to insert validations between the two steps.

I’ve implemented an example for you:

https://play.rust-lang.org/?gist=21301d9a85a23f88439ada011f0cee2f&version=stable


#4

@skade Thanks for the solution with example .Helped a lot . Much appreciated.