├── .gitignore ├── LICENSE ├── README.md ├── map2struct.go ├── map2struct_examples.go ├── map2struct_test.go ├── struct2map.go └── struct2map_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Getting Start 2 | 3 | This is a utility package of Golang provides convenient way to make conversion between maps and structs. There are two functions in this package: 4 | 5 | > func **Map2Struct**(m maps[string]interface{}, s interface{}) (error) 6 | 7 | Map2Struct() converts a map to struct. You can custom how the fields of the struct match the keys in the map in a very simple way. You can also specify a default value or report an error if the key is not found. 8 | 9 | > func **Struct2Map**(s interface{}) map[string]interface{} 10 | 11 | Struct2Map(), on the contrary, converts a struct into a map. This function is less powerful, honestly, but it's also helpful in some situations. 12 | 13 | To be clear, we use the term 'field' to indicate the field in struct. And we use term 'key' and 'value' to indicate key and value in map. 14 | 15 | # Map2Struct 16 | 17 | > func **Map2Struct**(m maps[string]interface{}, s interface{}) (error) 18 | 19 | This function converts a map into a struct. To use this function, import it first: 20 | 21 | ```golang 22 | import Map2Struct from mapstruct 23 | ``` 24 | 25 | Here is an example: 26 | 27 | ```golang 28 | m := map[string]interface{} { 29 | "Id" : 1001, 30 | "Name" : "tiaotiao", 31 | } 32 | 33 | s := struct { 34 | Id int64 // 1001 35 | Name string // "tiaotiao" 36 | }{} 37 | 38 | err := Map2Struct(m, &s) 39 | ``` 40 | 41 | The type of map must be map[string]interface{}. 42 | 43 | You can predefine the struct somewhere else, or just define a new type of struct where you need it. 44 | 45 | The second parameter must be a reference of the struct, so that it can be modified by the function. 46 | 47 | Map2Struct will go through all the fields of the struct one by one, to look up if is there any key in the map matches the field. If there is a key in the map matches, the function will assign the value to the field. 48 | 49 | By default, Map2Struct uses the exact name of the field to search for keys. It is case sensitive. 50 | 51 | If the type of value is not the same as the type of field, Map2Struct will try it best to convert and assign the value to the field. We will discuss it later. 52 | 53 | If a field is not found, it will stay unchanged by default. You are able to assign it a default value or report an error by giving the field a tag. 54 | 55 | Only [public fields](https://golang.org/doc/effective_go.html#names) of the struct will be processed. It means **fields starting with lowercase will be ignored**. 56 | 57 | ### Name Tags 58 | 59 | In most case, we want to custom another names for fields. For instance, if the field of struct is 'Name' but we want to match the key 'user_name' in the map. We can achieve this by giving the field a tag. 60 | 61 | ```golang 62 | struct { 63 | Id int64 `map:"user_id"` // search for "user_id" 64 | Name string `map:"user_name"` // search for "user_name" 65 | } 66 | ``` 67 | 68 | We use 'map' to indicate this tag is for our package. The following string within the quote is the customed name for the field which you want to search for in the map. 69 | 70 | Struct tag is a feature of Golang. You may probably see other [well known struct tags](https://github.com/golang/go/wiki/Well-known-struct-tags) like 'xml' or 'json' somewhere else. 71 | 72 | ### Ignore Field 73 | 74 | ```golang 75 | struct { 76 | Website string `map:"-"` // ignored 77 | } 78 | ``` 79 | 80 | Here is a special field tag "-" which indicate this field will be ignored by Map2Struct. If a field tag is "-", this field will always stay unchanged after the function call, even if there is a key in the map matches this field exactly. 81 | 82 | ### Default Value 83 | 84 | We are able to assign the field a default value if it's not found in the map. 85 | 86 | ```golang 87 | struct { 88 | Id int64 `map:"user_id,-1"` // default value is -1 89 | Name string `map:"user_name"` // no default value 90 | Blocked bool `map:"blocked,false"` // default value is false 91 | } 92 | ``` 93 | 94 | Default value can be defined followed by the field tag, separated by a comma. 95 | 96 | Default value only applies when field is not found. 97 | 98 | Since default value is defined as type of string, the function will try it best to convert it to the target type. It will return an error if the conversion is failed. 99 | 100 | ### Required 101 | 102 | If the we set "required" as default value, it indicates this field is required from the map. Map2Struct will return an error if it is not found. 103 | 104 | ```golang 105 | struct { 106 | Id int64 `map:"user_id,required"` 107 | Name string `map:"user_name,required"` 108 | } 109 | ``` 110 | 111 | This feature is really useful for me which simplifies my coding a lot. 112 | 113 | ### Type Conversion 114 | 115 | The following conversion rules apply to both map values and default values. 116 | 117 | First of all, Map2Struct will try to [assign](https://golang.org/ref/spec#Assignability) or [convert](https://golang.org/ref/spec#Conversions) it directly using standard Golang library. This step should cover most of the situations. 118 | 119 | If the first step failed, we expect that the value should be a string or json which can be interpreted to the target type. Otherwise it returns an error. 120 | 121 | Map2Struct use different methods to interpret a string value, based on type of the target field. 122 | 123 | - If the field is an integer, float or bool, we use [strconv.ParseInt()](https://golang.org/pkg/strconv/#ParseInt), [ParseUint()](https://golang.org/pkg/strconv/#ParseUint), [ParseFloat()](https://golang.org/pkg/strconv/#ParseFloat), [ParseBool()](https://golang.org/pkg/strconv/#ParseBool) to convert the string. 124 | - If the field is a struct, pointer, slice, slice of objects, etc., we interpret the string as a json using [json.Unmarshal()](https://golang.org/pkg/encoding/json/#Marshal). The value type can be a string or json.RawMessage. 125 | 126 | ```golang 127 | m := map[string]interface{}{ 128 | "user_ids": []int64{501, 502, 503}, 129 | "user_names": `["batman", "ironman", "superman"]`, 130 | "group_info": `{"id":1, "name":"heros"}`, 131 | "relative_groups": json.RawMessage(`[{"id":7, "name":"FBI"}, {"id":9, "name":"CIA"}]`), 132 | } 133 | 134 | s := struct { 135 | Ids []int64 `map:"user_ids"` // [501, 502, 503] 136 | Names []string `map:"user_names"` // ["batman", "ironman", "superman"] 137 | Group group_info `map:"group_info"` // {1, "heros"} 138 | Relatives []*group_info `map:"relative_groups"` // [{7, "FBI"}, {9, "CIA"}] 139 | }{} 140 | 141 | err := Map2Struct(m, &s) 142 | ``` 143 | 144 | # Struct2Map 145 | 146 | > func **Struct2Map**(s interface{}) map[string]interface{} 147 | 148 | This function converts a struct to map. To use this function, import it first: 149 | 150 | ```golang 151 | import Struct2Map from mapstruct 152 | ``` 153 | 154 | Here is an example: 155 | 156 | ```golang 157 | s := struct { 158 | Id int64 159 | Name string 160 | }{ 161 | Id : 1001, 162 | Name : "tiaotiao", 163 | } 164 | 165 | m := Struct2Map(s) 166 | /*{ 167 | "Id" : 1001, 168 | "Name": "tiaotiao", 169 | }*/ 170 | ``` 171 | 172 | Struct2Map will create and return a new map from the given struct. The keys of the map will be the name of fields. The values will be the value of fields. 173 | 174 | Only [public fields](https://golang.org/doc/effective_go.html#names) will be processed. So **fields starting with lowercase will be ignored**. 175 | 176 | ### Name Tags 177 | 178 | ```golang 179 | struct { 180 | Id int64 `map:"user_id"` 181 | Name string `map:"user_name"` 182 | } 183 | ``` 184 | 185 | We can give the field a tag to specicy another name to be used as the key. 186 | 187 | See Map2Struct above. 188 | 189 | ### Ignore Field 190 | 191 | ```golang 192 | struct { 193 | Other string `map:"-"` 194 | } 195 | ``` 196 | 197 | If we give the special tag "-" to a field, it will be ignored. 198 | 199 | ### Omit Empty 200 | 201 | ```golang 202 | struct { 203 | Description string `map:"desc,omitempty"` 204 | } 205 | ``` 206 | 207 | If tag option is "omitempty", this field will not appear in the map if the value is empty. 208 | 209 | Empty values are 0, false, "", nil, empty array and empty map. 210 | 211 | ### To String 212 | 213 | ```golang 214 | struct { 215 | Id int64 `map:"id,string"` 216 | Price float32 `map:"price,string"` 217 | } 218 | ``` 219 | 220 | If tag option is "string", this field will be convert to string type. Struct2Map will put the original value to the map if the conversion is failed. 221 | -------------------------------------------------------------------------------- /map2struct.go: -------------------------------------------------------------------------------- 1 | package mapstruct 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "reflect" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | const DefaultTag = "map" 12 | 13 | func Map2Struct(vals map[string]interface{}, dst interface{}) (err error) { 14 | return Map2StructTag(vals, dst, DefaultTag) 15 | } 16 | 17 | func Map2StructTag(vals map[string]interface{}, dst interface{}, tagName string) (err error) { 18 | defer func() { 19 | e := recover() 20 | if e != nil { 21 | if v, ok := e.(error); ok { 22 | err = errors.New("Panic: " + v.Error()) 23 | } else { 24 | err = errors.New("Panic: " + reflect.ValueOf(e).String()) 25 | } 26 | } 27 | }() 28 | 29 | pt := reflect.TypeOf(dst) 30 | pv := reflect.ValueOf(dst) 31 | 32 | if pv.Kind() != reflect.Ptr || pv.Elem().Kind() != reflect.Struct { 33 | return errors.New("Not a pointer of struct") 34 | //return fmt.Errorf("not a pointer of struct") 35 | } 36 | 37 | var f reflect.StructField 38 | var fv reflect.Value 39 | 40 | for i := 0; i < pt.Elem().NumField(); i++ { 41 | f = pt.Elem().Field(i) 42 | fv = pv.Elem().Field(i) 43 | 44 | if f.Anonymous { 45 | continue 46 | } 47 | 48 | if !fv.CanSet() { 49 | continue 50 | } 51 | 52 | tag := f.Tag.Get(tagName) 53 | name, option := parseTag(tag) 54 | 55 | if name == "" { 56 | // tag name is not set, use field name 57 | name = f.Name 58 | } 59 | 60 | err = map2Field(vals, fv, name, option) 61 | if err != nil { 62 | return errors.New("field " + name + "(" + fv.Type().Kind().String() + ") error: " + err.Error()) 63 | } 64 | 65 | continue 66 | } 67 | 68 | return nil 69 | } 70 | 71 | func Map2Field(vals map[string]interface{}, dst interface{}, tag string) error { 72 | fv := reflect.ValueOf(dst) 73 | if fv.Kind() != reflect.Ptr { 74 | return errors.New("dst must be a pointer") 75 | } 76 | 77 | name, option := parseTag(tag) 78 | 79 | return map2Field(vals, fv, name, option) 80 | } 81 | 82 | func map2Field(vals map[string]interface{}, fv reflect.Value, name, option string) error { 83 | if name == "-" || name == "" { 84 | return nil // ignore "-" 85 | } 86 | 87 | // value from map 88 | val, ok := vals[name] 89 | if !ok { 90 | val, ok = vals[strings.ToLower(name)] 91 | } 92 | 93 | if !ok { // value not found 94 | if option == "required" { 95 | return errors.New("'" + name + "' is required") 96 | } 97 | 98 | if len(option) != 0 { 99 | val = option // 'option' means 'default value' here 100 | } else { 101 | return nil // ignore it 102 | } 103 | } 104 | 105 | return convert(val, fv) 106 | } 107 | 108 | // Convert varies types of value to a certain type. 109 | // Value can be type of string or json or whatever type which is convertable to the target type. 110 | func Convert(dst interface{}, val interface{}) error { 111 | fv := reflect.ValueOf(dst) 112 | if fv.Type().Kind() != reflect.Ptr { 113 | return errors.New("dst must be a pointer") 114 | } 115 | return convert(val, fv) 116 | } 117 | 118 | func convert(val interface{}, fv reflect.Value) (err error) { 119 | // assign or convert value to field 120 | if assignToField(val, fv) == nil { 121 | return nil 122 | } 123 | 124 | switch v := val.(type) { 125 | case string: 126 | // parse string to value 127 | s := strings.TrimSpace(v) 128 | err = convertStringToValue(s, fv, fv.Type().Kind()) 129 | 130 | case json.RawMessage: 131 | // unmarshal json 132 | err = convertJsonToValue(v, fv) 133 | 134 | default: 135 | err = errors.New("value type is not supported: value=" + reflect.ValueOf(val).Kind().String()) 136 | } 137 | 138 | return err 139 | } 140 | 141 | func assignToField(val interface{}, fv reflect.Value) error { 142 | vv := reflect.ValueOf(val) 143 | vt := reflect.TypeOf(val) 144 | ft := fv.Type() 145 | 146 | // assign or convert value to field 147 | if vt.AssignableTo(ft) { 148 | fv.Set(vv) 149 | return nil 150 | } 151 | if vt.ConvertibleTo(ft) { 152 | fv.Set(vv.Convert(ft)) 153 | return nil 154 | } 155 | return errors.New("Can not assign: valueKind = " + vt.Kind().String()) 156 | // Loss of info, below. Is it required or commonly useful? Worth fmt? 157 | //return fmt.Errorf("can not assign: value=%v(%v)", val, vt.Kind()) 158 | } 159 | 160 | func convertJsonToValue(data json.RawMessage, fv reflect.Value) error { 161 | var err error 162 | 163 | if fv.Kind() == reflect.Ptr { 164 | if fv.IsNil() { 165 | fv.Set(reflect.New(fv.Type().Elem())) 166 | } 167 | } else { 168 | fv = fv.Addr() 169 | } 170 | 171 | err = json.Unmarshal(data, fv.Interface()) 172 | 173 | if err != nil { 174 | return errors.New("Invalid json: " + err.Error() + ", " + string(data)) 175 | } 176 | 177 | return nil 178 | } 179 | 180 | func convertStringToValue(s string, fv reflect.Value, kind reflect.Kind) error { 181 | if !fv.CanAddr() { 182 | return errors.New("Target can not addr") 183 | } 184 | 185 | if assignToField(s, fv) == nil { 186 | return nil 187 | } 188 | 189 | if kind == reflect.String { 190 | fv.SetString(s) 191 | return nil 192 | } 193 | 194 | if kind == reflect.Slice { 195 | return convertStringToSlice(s, fv) 196 | } 197 | 198 | if kind == reflect.Ptr || kind == reflect.Struct { 199 | return convertJsonToValue(json.RawMessage(s), fv) 200 | } 201 | 202 | if kind == reflect.Bool { 203 | switch strings.ToLower(s) { 204 | case "true": 205 | fv.SetBool(true) 206 | case "false": 207 | fv.SetBool(false) 208 | case "1": 209 | fv.SetBool(true) 210 | case "0": 211 | fv.SetBool(false) 212 | default: 213 | return errors.New("Invalid bool: value=" + s) 214 | } 215 | return nil 216 | } 217 | 218 | if reflect.Int <= kind && kind <= reflect.Int64 { 219 | i, err := strconv.ParseInt(s, 10, 64) 220 | if err != nil { 221 | return errors.New("Invalid int: value=" + s) 222 | } 223 | fv.SetInt(i) 224 | 225 | } else if reflect.Uint <= kind && kind <= reflect.Uint64 { 226 | i, err := strconv.ParseUint(s, 10, 64) 227 | if err != nil { 228 | return errors.New("Invalid uint: value=" + s) 229 | } 230 | fv.SetUint(i) 231 | 232 | } else if reflect.Float32 == kind || kind == reflect.Float64 { 233 | i, err := strconv.ParseFloat(s, 64) 234 | if err != nil { 235 | return errors.New("Invalid float: value=" + s) 236 | } 237 | fv.SetFloat(i) 238 | 239 | } else { 240 | // type not support 241 | return errors.New("Type not supported: value=" + s) 242 | } 243 | return nil 244 | } 245 | 246 | func convertStringToSlice(s string, fv reflect.Value) error { 247 | var err error 248 | ft := fv.Type() 249 | et := ft.Elem() 250 | 251 | if len(s) == 0 { 252 | return nil 253 | } 254 | 255 | data := json.RawMessage(s) 256 | if data[0] == '[' && data[len(data)-1] == ']' { 257 | return convertJsonToValue(data, fv) 258 | } 259 | 260 | ss := strings.Split(s, ",") 261 | fs := reflect.MakeSlice(ft, 0, len(ss)) 262 | 263 | for _, si := range ss { 264 | ev := reflect.New(et).Elem() 265 | 266 | err = convertStringToValue(si, ev, et.Kind()) 267 | if err != nil { 268 | return err 269 | } 270 | fs = reflect.Append(fs, ev) 271 | } 272 | 273 | fv.Set(fs) 274 | 275 | return nil 276 | } 277 | 278 | func parseTag(tag string) (string, string) { 279 | tags := strings.Split(tag, ",") 280 | 281 | if len(tags) <= 0 { 282 | return "", "" 283 | } 284 | 285 | if len(tags) == 1 { 286 | return tags[0], "" 287 | } 288 | 289 | return tags[0], tags[1] 290 | } 291 | -------------------------------------------------------------------------------- /map2struct_examples.go: -------------------------------------------------------------------------------- 1 | package mapstruct 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | func map2struct_example_1() error { // basic 8 | m := map[string]interface{}{ 9 | "Id": 1001, 10 | "Name": "tiaotiao", 11 | } 12 | 13 | s := struct { 14 | Id int64 // 1001 15 | Name string // "tiaotiao" 16 | }{} 17 | 18 | return Map2Struct(m, &s) 19 | } 20 | 21 | func map2struct_example_2() error { // not match 22 | m := map[string]interface{}{ 23 | "Id": 1001, 24 | "name": "tiaotiao", 25 | } 26 | 27 | s := struct { 28 | ID int64 // 0 case sensitive 29 | name string // "" ignore fields starting with lower case 30 | }{} 31 | 32 | return Map2Struct(m, &s) 33 | } 34 | 35 | func map2struct_example_3() error { // using tag 36 | m := map[string]interface{}{ 37 | "user_id": 1001, 38 | "user_name": "tiaotiao", 39 | "user_website": "https://github.com/tiaotiao", 40 | } 41 | 42 | s := struct { 43 | Id int64 `map:"user_id"` // 1001 search for "user_id" 44 | Name string `map:"user_name"` // "tiaotiao" search for "user_name" 45 | Website string `map:"-"` // "" alway ignore "-" 46 | }{} 47 | 48 | return Map2Struct(m, &s) 49 | } 50 | 51 | func map2struct_example_4() error { // default value 52 | m := map[string]interface{}{ 53 | "user_id": 1001, 54 | "user_name": "tiaotiao", 55 | } 56 | 57 | s := struct { 58 | Id int64 `map:"user_id,-1"` // 1001 will be -1 if not found 59 | Name string `map:"user_name,required"` // "tiaotiao" will return an error if not found 60 | // "required" is the only reserved word which cannot be used as default value 61 | UserType string `map:"desc,normal"` // "normal" use default value 62 | Blocked bool `map:"blocked,false"` // false use default value 63 | }{} 64 | 65 | return Map2Struct(m, &s) 66 | } 67 | 68 | type group_info struct { 69 | Id int64 `json:"id"` 70 | Name string `json:"name"` 71 | } 72 | 73 | func map2struct_example_5() error { // advanced 74 | m := map[string]interface{}{ 75 | "user_ids": []int64{501, 502, 503}, 76 | "user_names": `["batman", "ironman", "superman"]`, 77 | "group_info": `{"id":1, "name":"heros"}`, 78 | "relative_groups": json.RawMessage(`[{"id":7, "name":"FBI"}, {"id":9, "name":"CIA"}]`), 79 | } 80 | 81 | s := struct { 82 | Ids []int64 // [501, 502, 503] support array 83 | Names []string // ["batman", "ironman", "superman"] support json string 84 | Group group_info // {1, "heros"} support object from json string 85 | Relatives []*group_info // [{7, "FBI"}, {9, "CIA"}] support pointer 86 | }{} 87 | 88 | return Map2Struct(m, &s) 89 | } 90 | -------------------------------------------------------------------------------- /map2struct_test.go: -------------------------------------------------------------------------------- 1 | package mapstruct 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "reflect" 7 | "testing" 8 | ) 9 | 10 | func TestMap2Struct(t *testing.T) { 11 | var args = struct { 12 | // basic 13 | Id int64 `map:"id,required"` 14 | Name string `map:"name,required"` 15 | IsOK bool `map:"ok"` 16 | Price float64 `map:"price"` 17 | 18 | // options 19 | Ignore string `map:"-"` 20 | NoName string 21 | NoValue int64 `map:"novalue,1002"` // default value is "1002" 22 | }{} 23 | 24 | var vals = map[string]interface{}{ 25 | "id": 1001, 26 | "name": "tom", 27 | "ok": true, 28 | "price": 29.9, 29 | 30 | "ignore": "never mind", // discard 31 | "NoName": "hello", 32 | "NotFound": "never mind", // discard 33 | } 34 | 35 | // check 36 | check := args 37 | check.Id = 1001 38 | check.Name = "tom" 39 | check.IsOK = true 40 | check.Price = 29.9 41 | check.Ignore = "" 42 | check.NoName = "hello" 43 | check.NoValue = 1002 44 | 45 | checkMap2Struct(vals, &args, check, t) 46 | 47 | //////////////////////////////////////////////////////////// 48 | 49 | var argsSlice = struct { 50 | 51 | // slice 52 | Tags []string `map:"tags"` 53 | Ids []int64 `map:"ids"` 54 | Things []interface{} `map:"things"` 55 | }{} 56 | 57 | var valsSlice = map[string]interface{}{ 58 | // string slice 59 | "tags": "edu,zhuhai,trees", 60 | "ids": "10,20,30", 61 | } 62 | 63 | checkSlice := argsSlice 64 | checkSlice.Tags = []string{"edu", "zhuhai", "trees"} 65 | checkSlice.Ids = []int64{10, 20, 30} 66 | 67 | checkMap2Struct(valsSlice, &argsSlice, checkSlice, t) 68 | 69 | //////////////////////////////////////////////////////////// 70 | 71 | var argsJson struct { 72 | 73 | // json 74 | Book BookInfo `map:"book"` 75 | Books []*BookInfo `map:"books"` 76 | BookNames []string `map:"booknames"` 77 | } 78 | 79 | var valsJson = map[string]interface{}{ 80 | // json 81 | "book": json.RawMessage(`{"id":2001, "name":"harry poter"}`), 82 | "books": `[{"id":3001, "name":"python programming"}, {"id":3002, "name":"cooking book"}]`, 83 | "booknames": `["c programming","thinking in java"]`, 84 | } 85 | 86 | checkJson := argsJson 87 | checkJson.Book = BookInfo{2001, "harry poter"} 88 | checkJson.Books = []*BookInfo{{3001, "python programming"}, {3002, "cooking book"}} 89 | checkJson.BookNames = []string{"c programming", "thinking in java"} 90 | 91 | checkMap2Struct(valsJson, &argsJson, checkJson, t) 92 | } 93 | 94 | func TestMap2StructExamples(t *testing.T) { 95 | var e error 96 | e = map2struct_example_1() 97 | if e != nil { 98 | t.Error("example1", e) 99 | } 100 | e = map2struct_example_2() 101 | if e != nil { 102 | t.Error("example2", e) 103 | } 104 | e = map2struct_example_3() 105 | if e != nil { 106 | t.Error("example3", e) 107 | } 108 | e = map2struct_example_4() 109 | if e != nil { 110 | t.Error("example4", e) 111 | } 112 | e = map2struct_example_5() 113 | if e != nil { 114 | t.Error("example5", e) 115 | } 116 | } 117 | 118 | func checkMap2Struct(vals map[string]interface{}, args interface{}, check interface{}, t *testing.T) { 119 | err := Map2Struct(vals, args) 120 | if err != nil { 121 | t.Fatal(err.Error()) 122 | } 123 | 124 | checkEqual(args, check, t) 125 | } 126 | 127 | func checkEqual(v1, v2 interface{}, t *testing.T) { 128 | rv1 := reflect.ValueOf(v1) 129 | rv2 := reflect.ValueOf(v2) 130 | if rv1.Kind() == reflect.Ptr { 131 | rv1 = rv1.Elem() 132 | } 133 | if rv2.Kind() == reflect.Ptr { 134 | rv2 = rv2.Elem() 135 | } 136 | 137 | for i := 0; i < rv1.NumField(); i++ { 138 | fv1 := rv1.Field(i).Interface() 139 | fv2 := rv2.Field(i).Interface() 140 | 141 | if !reflect.DeepEqual(fv1, fv2) { 142 | t.Fatal(fmt.Sprintf("not equal. %v: %#v!=%#v --> %v != %v \n", rv1.Type().Field(i).Name, fv1, fv2, v1, v2)) 143 | } 144 | } 145 | } 146 | 147 | type BookInfo struct { 148 | ID int64 `json:"id"` 149 | Name string `json:"name"` 150 | } 151 | -------------------------------------------------------------------------------- /struct2map.go: -------------------------------------------------------------------------------- 1 | package mapstruct 2 | 3 | import ( 4 | "reflect" 5 | "strconv" 6 | ) 7 | 8 | func Struct2Map(s interface{}) map[string]interface{} { 9 | return Struct2MapTag(s, DefaultTag) // TODO use different tag? 10 | } 11 | 12 | func Struct2MapTag(s interface{}, tagName string) map[string]interface{} { 13 | t := reflect.TypeOf(s) 14 | v := reflect.ValueOf(s) 15 | 16 | if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { 17 | t = t.Elem() 18 | v = v.Elem() 19 | } 20 | 21 | if v.Kind() != reflect.Struct { 22 | return nil 23 | } 24 | 25 | m := make(map[string]interface{}) 26 | 27 | for i := 0; i < t.NumField(); i++ { 28 | fv := v.Field(i) 29 | ft := t.Field(i) 30 | 31 | if !fv.CanInterface() { 32 | continue 33 | } 34 | 35 | if ft.PkgPath != "" { // unexported 36 | continue 37 | } 38 | 39 | var name string 40 | var option string 41 | 42 | name, option = parseTag(ft.Tag.Get(tagName)) 43 | 44 | if name == "-" { 45 | continue // ignore "-" 46 | } 47 | 48 | if name == "" { 49 | name = ft.Name // use field name 50 | } 51 | 52 | if option == "omitempty" { 53 | if isEmpty(&fv) { 54 | continue // skip empty field 55 | } 56 | } 57 | 58 | // ft.Anonymous means embedded field 59 | if ft.Anonymous { 60 | if fv.Kind() == reflect.Ptr && fv.IsNil() { 61 | continue // nil 62 | } 63 | 64 | if (fv.Kind() == reflect.Struct) || 65 | (fv.Kind() == reflect.Ptr && fv.Elem().Kind() == reflect.Struct) { 66 | 67 | // embedded struct 68 | embedded := Struct2MapTag(fv.Interface(), tagName) 69 | 70 | for embName, embValue := range embedded { 71 | m[embName] = embValue 72 | } 73 | } 74 | continue 75 | } 76 | 77 | if option == "string" { 78 | s := toString(fv) 79 | if s != nil { 80 | m[name] = s 81 | continue 82 | } 83 | } 84 | 85 | m[name] = fv.Interface() 86 | } 87 | 88 | return m 89 | } 90 | 91 | func toString(fv reflect.Value) interface{} { 92 | kind := fv.Kind() 93 | if kind == reflect.Int || kind == reflect.Int8 || kind == reflect.Int16 || kind == reflect.Int32 || kind == reflect.Int64 { 94 | return strconv.FormatInt(fv.Int(), 10) 95 | } else if kind == reflect.Uint || kind == reflect.Uint8 || kind == reflect.Uint16 || kind == reflect.Uint32 || kind == reflect.Uint64 { 96 | return strconv.FormatUint(fv.Uint(), 10) 97 | } else if kind == reflect.Float32 || kind == reflect.Float64 { 98 | return strconv.FormatFloat(fv.Float(), 'f', 2, 64) 99 | } 100 | // TODO support more types 101 | return nil 102 | } 103 | 104 | func isEmpty(v *reflect.Value) bool { 105 | k := v.Kind() 106 | if k == reflect.Bool { 107 | return v.Bool() == false 108 | } else if reflect.Int < k && k < reflect.Int64 { 109 | return v.Int() == 0 110 | } else if reflect.Uint < k && k < reflect.Uintptr { 111 | return v.Uint() == 0 112 | } else if k == reflect.Float32 || k == reflect.Float64 { 113 | return v.Float() == 0 114 | } else if k == reflect.Array || k == reflect.Map || k == reflect.Slice || k == reflect.String { 115 | return v.Len() == 0 116 | } else if k == reflect.Interface || k == reflect.Ptr { 117 | return v.IsNil() 118 | } 119 | return false 120 | } 121 | -------------------------------------------------------------------------------- /struct2map_test.go: -------------------------------------------------------------------------------- 1 | package mapstruct 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestStruct2Map(t *testing.T) { 10 | var args = struct { 11 | Id int64 `map:"id"` 12 | Name string `map:"name"` 13 | IsOK bool `map:"ok"` 14 | OmitEmpty string `map:"empty,omitempty"` // discard 15 | Ignore string `map:"-"` // discard 16 | NoName string 17 | StringInt int64 `map:"strint,string"` 18 | }{ 19 | Id: 1001, 20 | Name: "tim", 21 | IsOK: true, 22 | OmitEmpty: "", 23 | Ignore: "never mind", 24 | NoName: "hello", 25 | StringInt: 2001, 26 | } 27 | 28 | var check = map[string]interface{}{ 29 | "id": int64(1001), 30 | "name": "tim", 31 | "ok": true, 32 | "NoName": "hello", 33 | "strint": "2001", 34 | } 35 | 36 | vals := Struct2Map(args) 37 | 38 | checkStruct2Map(vals, check, t) 39 | } 40 | 41 | func checkStruct2Map(vals, check map[string]interface{}, t *testing.T) { 42 | for k, v := range check { 43 | cv, ok := vals[k] 44 | if !ok { 45 | t.Fatal(fmt.Sprintf("key [%v] not found, %v", k, v)) 46 | } 47 | 48 | if !reflect.DeepEqual(v, cv) { 49 | t.Fatal(fmt.Sprintf("not equal [%v]: %v != %v", k, v, cv)) 50 | } 51 | 52 | delete(check, k) 53 | delete(vals, k) 54 | } 55 | 56 | if len(vals) > 0 { 57 | t.Fatal(fmt.Sprintf("unexpected vals [%v]", vals)) 58 | } 59 | } 60 | --------------------------------------------------------------------------------