Advertisement
pakuula

Serializer

Feb 10th, 2021
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. package org.example.query;
  2.  
  3. import java.io.UnsupportedEncodingException;
  4. import java.net.URLEncoder;
  5. import java.nio.charset.StandardCharsets;
  6.  
  7. public class Serializer {
  8.     public static String urlEncode(String text) {
  9.         try {
  10.             return URLEncoder.encode(text, StandardCharsets.UTF_8.toString());
  11.         } catch (UnsupportedEncodingException e) {
  12.             throw new RuntimeException("Should never happen", e);
  13.         }
  14.     }
  15.  
  16.     public static String buildQuery(Object obj) throws SerializerException {
  17.         StringBuilder result = new StringBuilder();
  18.        
  19.         for (java.lang.reflect.Field fld : obj.getClass().getFields()) {
  20.             QueryField annot = fld.getAnnotation(QueryField.class);
  21.             if (annot == null) {
  22.                 // This field has no "Field" annotation, ignore it.
  23.                 continue;
  24.             }
  25.            
  26.             Object fldVal;
  27.             try {
  28.                 fldVal = fld.get(obj);
  29.             } catch (IllegalArgumentException e) {
  30.                 throw new RuntimeException("Should never happen", e);
  31.             } catch (IllegalAccessException e) {
  32.                 // TODO Auto-generated catch block
  33.                 throw new SerializerException("Failed to access field "+fld.getName(), e);
  34.             }
  35.            
  36.             if (fldVal == null) {
  37.                 if (annot.required()) {
  38.                     throw new SerializerException("Required field is null");
  39.                 } else {
  40.                     // Ignore optional fields
  41.                     continue;
  42.                 }
  43.             }
  44.            
  45.             String valText = urlEncode(fldVal.toString());
  46.            
  47.             String valName = annot.name();
  48.             if (valName.length() == 0) {
  49.                 // No custom name, use field name instead
  50.                 valName = fld.getName();
  51.             }
  52.             valName = urlEncode(valName);
  53.            
  54.             result.append('&').append(valName).append('=').append(valText);
  55.         }
  56.         return result.substring(1);
  57.     }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement