@@ -77,28 +77,30 @@ pub struct JsonReply {
7777 error_code : ErrorCode ,
7878 /// The error message to be displayed only in debug logs
7979 message : String ,
80- /// Additional fields to be added to the JSON
81- additional_fields : Vec < String > ,
80+ /// Additional fields to be included in the JSON response
81+ extra : serde_json :: Map < String , serde_json :: Value > ,
8282}
8383
8484impl JsonReply {
8585 /// Create a new Reply
8686 pub fn new ( error_code : ErrorCode , message : impl fmt:: Display ) -> Self {
87- Self { error_code, message : message. to_string ( ) , additional_fields : vec ! [ ] }
87+ Self { error_code, message : message. to_string ( ) , extra : serde_json:: Map :: new ( ) }
88+ }
89+
90+ /// Add an additional field to the JSON response
91+ pub fn with_extra ( mut self , key : & str , value : impl Into < serde_json:: Value > ) -> Self {
92+ self . extra . insert ( key. to_string ( ) , value. into ( ) ) ;
93+ self
8894 }
8995
9096 /// Serialize the Reply to a JSON string
91- pub fn to_json ( & self ) -> String {
92- if self . additional_fields . is_empty ( ) {
93- format ! ( r#"{{ "errorCode": "{}", "message": "{}" }}"# , self . error_code, self . message)
94- } else {
95- format ! (
96- r#"{{ "errorCode": "{}", "message": "{}", {} }}"# ,
97- self . error_code,
98- self . message,
99- self . additional_fields. join( ", " )
100- )
101- }
97+ pub fn to_json ( & self ) -> serde_json:: Value {
98+ let mut map = serde_json:: Map :: new ( ) ;
99+ map. insert ( "errorCode" . to_string ( ) , self . error_code . to_string ( ) . into ( ) ) ;
100+ map. insert ( "message" . to_string ( ) , self . message . clone ( ) . into ( ) ) ;
101+ map. extend ( self . extra . clone ( ) ) ;
102+
103+ serde_json:: Value :: Object ( map)
102104 }
103105}
104106
@@ -205,14 +207,8 @@ impl From<&PayloadError> for JsonReply {
205207 super :: optional_parameters:: Error :: UnknownVersion { supported_versions } => {
206208 let supported_versions_json =
207209 serde_json:: to_string ( supported_versions) . unwrap_or_default ( ) ;
208- JsonReply {
209- error_code : VersionUnsupported ,
210- message : "This version of payjoin is not supported." . to_string ( ) ,
211- additional_fields : vec ! [ format!(
212- r#""supported": {}"# ,
213- supported_versions_json
214- ) ] ,
215- }
210+ JsonReply :: new ( VersionUnsupported , "This version of payjoin is not supported." )
211+ . with_extra ( "supported" , supported_versions_json)
216212 }
217213 _ => JsonReply :: new ( OriginalPsbtRejected , e) ,
218214 } ,
0 commit comments