use native_json::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
type Pod<T = (), E = anyhow::Error> = core::result::Result<T, E>;
#[test]
fn json_optional_field() -> Pod {
json! {
Order {
state: i32?, type_: i32, proxy: bool?
}}
let mut order = Order::new();
assert!(order.type_ == 0);
let s = order.string()?;
assert!(s == "{\"type\":0}");
let s = "{\"type\":0,\"state\":100}";
order = serde_json::from_str(s)?;
assert!(order.state == 100);
assert!(order.proxy == false);
Ok(())
}
#[test]
fn json_reserved_keywords() -> Pod {
json! {
Order {
type_: String
}
}
let mut order = Order::new();
order.type_ = "LIMIT".into();
let s = order.string()?;
assert!(s == "{\"type\":\"LIMIT\"}");
let mut json = json! {
type_ : "Action"
};
let s = json.string()?;
assert!(s == "{\"type\":\"Action\"}");
json.type_ = "".into();
json = serde_json::from_str(&s)?;
assert!(json.type_ == "Action");
Ok(())
}
#[test]
fn json_instance() {
let mut json = json! {
name: "native json",
students: [
{name: "John", age: 17},
{name: "Jack", age: 20}
],
array: [1,2,3,4,5],
vector: vec![5,4,3,2,1],
hashmap: HashMap::from([("a", 1), ("b", 2), ("c", 3)]),
rect: {x: 10, y: 10, width: 100, height: 50}
};
json.students[0].age += 1;
json.rect.x += 10;
json.name = "Native JSON";
}
#[test]
fn json_declare() {
json! {
School {
name: String,
students:[{
name: String,
age: i32,
tutor: {
name: String,
course: String
}
},
...
],
nullable: Option<String>,
map: HashMap<String, i32>
}}
let mut school = School::new();
school.name = "MIT".to_owned();
let mut newbie = School_students_item::new();
let tutor = School_students_item_tutor {
name: "Don Markuson".to_owned(),
course: "Math".to_owned(),
};
newbie.name = "John".to_owned();
newbie.age = 17;
newbie.tutor = tutor;
school.students.push(newbie);
}
#[test]
fn json_serialize() -> Pod {
let mut json = json! {
name: "native json",
point: { x: 10, y: 20},
array: [1,2,3,4,5],
vector: vec![1,2,3,4,5,6]
};
let s = json.stringify(4)?;
json.name = "";
json = native_json::parse(&s)?;
assert_eq!(json.name, "native json");
let s2 = json.string()?;
json.name = "modified";
json = native_json::parse(&s2)?;
assert_eq!(json.name, "native json");
Ok(())
}
#[test]
fn json_test_array_with_custom_type() -> Result<(), std::io::Error> {
json! {
Student { name: String, age: u32}
}
json! {
Class {
name: String,
students: [Student]
}
}
let mut c = Class::new();
c.name = "High School".into();
let mut student = Student::new();
student.name = "Tom Jackson".into();
student.age = 25;
c.students.push(student);
Ok(())
}
#[test]
fn json_test_inline_comment() {
println!("should compile");
json! {
AggTrage {
e: String, E: i64, s: String, a: i64, p: String, q: String, f: i64, l: i64, T: i64, m: bool, c: char, }}
}