stepancheg / rust-protobuf

Rust implementation of Google protocol buffers
MIT License
2.81k stars 382 forks source link

How to keep attribute names underlined after function print_to_string in protobuf_json_mapping #718

Closed ape-casear closed 7 months ago

ape-casear commented 7 months ago

given a proto

package pa;
message Token {
    optional string token_id = 1;
    oneof value {
        uint32   int_value    = 2;
        bool   bool_value    = 3;
    }
}

lib.rs

pub fn proto_to_json() {
    let mut t = pa::Token::new();

    t.set_token_id("I am token".to_string());
    t.set_bool_value(true);

    match print_to_string(&t) {
        Ok(str) => {
            println!("json is {}", str);
            //  output: json is {"tokenId": "我是token", "boolValue": true}
        }
        Err(e) => {
            eprintln!("e is {}", e);
        }
    }
}

I need the output to be {"token_id": "我是token", "bool_value": true}

how to approach that?

ape-casear commented 7 months ago

found out

pub fn proto_to_json() {
   let mut t = pa::Token::new();

    t.set_token_id("我是token".to_string());
    t.set_bool_value(true);
    t.set_herAge("23".to_string());

    let options = PrintOptions {
        proto_field_name: true,
        ..Default::default()
    };
    println!("default is {:?}", options);
    match print_to_string_with_options(&t, &options) {
        Ok(str) => {
            println!("json is {}", str);
        }
        Err(e) => {
            eprintln!("e is {}", e);
        }
    }
}

the solution is passing PrintOptions to fn print_to_string_with_options.