{"id":906,"date":"2014-01-26T13:30:43","date_gmt":"2014-01-26T12:30:43","guid":{"rendered":"http:\/\/oprsteny.cz\/?p=906"},"modified":"2014-01-26T13:30:43","modified_gmt":"2014-01-26T12:30:43","slug":"java-json-serialization","status":"publish","type":"post","link":"https:\/\/oprsteny.cz\/?p=906","title":{"rendered":"Java &#8211; JSON serialization"},"content":{"rendered":"<p><img loading=\"lazy\" decoding=\"async\" data-attachment-id=\"897\" data-permalink=\"https:\/\/oprsteny.cz\/?attachment_id=897\" data-orig-file=\"https:\/\/oprsteny.cz\/wp-content\/uploads\/eclipse.png\" data-orig-size=\"44,42\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}\" data-image-title=\"Java\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/oprsteny.cz\/wp-content\/uploads\/eclipse.png\" class=\"size-full wp-image-897 alignleft\" alt=\"Java\" src=\"http:\/\/oprsteny.cz\/wp-content\/uploads\/eclipse.png\" width=\"44\" height=\"42\" \/>In this article I&#8217;d like to present:<\/p>\n<ul>\n<li>Example of Object serialization into JSON string<\/li>\n<li>Deserialization of JSON string to the Object<\/li>\n<\/ul>\n<p><!--more--><br \/>\nI created a class called <em>Person<\/em> where I&#8217;d like to keep some data about a person. Some of the fields are auto-generated and I don&#8217;t want them in the exported JSON string. Therefore I have to mark the fields required to be in output JSON using i.e. my own annotations:<\/p>\n<pre lang=\"java\">public class Person extends JSONModel {\r\n\/\/This field is NOT to be put in output JSON string  \r\n  public int id;\r\n\r\n\/\/This is an own annotation declared in parent class\r\n  @JSONField\r\n  public String name;\r\n\r\n  @JSONField\r\n  public int age;\r\n}<\/pre>\n<p>Here comes the important part &#8211; definition of the parent abstract class <em>JSONModel<\/em>.<\/p>\n<ul>\n<li>It implements interface of <em>org.json.JSONString<\/em> and its method <em>toJSONString()<\/em><\/li>\n<li>It defines protected annotation <em>JSONField<\/em> which is used in child classes to mark fields required in JSON output string.<\/li>\n<li>It implements method <em>fromJSONString(String tree)<\/em> for parsing and mapping given JSON string to the class instance.<\/li>\n<\/ul>\n<pre lang=\"java\">import java.lang.annotation.ElementType;\r\nimport java.lang.annotation.Retention;\r\nimport java.lang.annotation.RetentionPolicy;\r\nimport java.lang.annotation.Target;\r\nimport java.lang.reflect.Field;\r\n\r\nimport org.json.JSONException;\r\nimport org.json.JSONObject;\r\nimport org.json.JSONString;\r\n\r\npublic abstract class JSONModel implements JSONString{\r\n  @Target(ElementType.FIELD)\r\n  @Retention(RetentionPolicy.RUNTIME)\r\n  protected @interface JSONField { }\r\n\r\n  @Override\r\n  public String toJSONString() {\r\n    JSONObject model = new JSONObject();\r\n\/\/  Get all attributes of current class\r\n    Field[] fields = this.getClass().getDeclaredFields();\r\n\r\n    for (Field field : fields) {\r\n\/\/    Process only fields marked with the required annotation\r\n      if (field.isAnnotationPresent(JSONField.class)) {\r\n        try {\r\n\/\/        Add the attribute to JSON output\r\n          model.put(field.getName(), field.get(this));\r\n        } catch (IllegalArgumentException | IllegalAccessException | JSONException e) {\r\n          e.printStackTrace();\r\n        }\r\n      }\r\n    }\r\n\r\n    return model.toString();\r\n  }\r\n\r\n  private void setProperty(Object clazz, String fieldName, Object columnValue) {\r\n\/\/  This method sets attribute of clazz (class instance) to given value \r\n    try {\r\n      Field field = clazz.getClass().getDeclaredField(fieldName);\t\t\r\n\r\n\/\/    This is necessary in case the class atttribute has private visibility\r\n      field.setAccessible(true);\r\n      field.set(clazz, columnValue);\r\n    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {\r\n      e.printStackTrace();\r\n    }\t\r\n  }\t\r\n\r\n  public void fromJSONString(String tree){\r\n    JSONObject model;\r\n    try {\r\n\/\/    Parse given JSON string\r\n      model = new JSONObject(tree);\r\n    } catch (JSONException e) {\r\n      e.printStackTrace();\r\n      System.err.println(\"Given JSON string cannot be parsed back to Object\");\r\n      return;\r\n    }\r\n\r\n\/\/  Get all attributes of current class \r\n    Field[] fields = this.getClass().getDeclaredFields();\r\n    for (Field field : fields) {\r\n\/\/    Process only fields marked with the required annotation\r\n      if (field.isAnnotationPresent(JSONField.class)) {\t\t\t\t\r\n        try {\r\n\/\/        Set new value of the class instance attribute\r\n          this.setProperty(this, field.getName(), model.get(field.getName()));\r\n        } catch (JSONException e) {\r\n\te.printStackTrace();\r\n        }\r\n      }\r\n    }\t\t\t\r\n  }\r\n}<\/pre>\n<p>We can make a simple test:<\/p>\n<ol>\n<li>Create 1<sup>st<\/sup> person with all attributes filled in<\/li>\n<li>Create 2<sup>nd<\/sup> person with all attributes filled in<\/li>\n<li>Create 3<sup>rd<\/sup> person from JSON string generated from 2<sup>nd<\/sup> person<\/li>\n<\/ol>\n<pre lang=\"java\">public class Main {\r\n  public static void main(String[] args) {\r\n    Person p1 = new Person();\r\n    p1.id  = 1;\r\n    p1.name = \"John\";\r\n    p1.age  = 30;\r\n\r\n    Person p2 = new Person();\r\n    p2.id  = 2;\r\n    p2.name = \"Mike\";\r\n    p2.age  = 47;\r\n    String p2JSON = p2.toJSONString();\r\n\r\n    Person p3 = new Person();\r\n    p3.fromJSONString(p2JSON);\r\n\r\n    System.out.println(\"P1: \" + p1.toJSONString());\r\n    System.out.println(\"P2: \" + p2JSON);\r\n    System.out.println(\"P3: \" + p3.toJSONString());\r\n  }\r\n}<\/pre>\n<p>In output you can see that only attributes marked in class <em>Person<\/em> with annotation <em>JSONField<\/em> are present in the output JSON string. The 3<sup>rd<\/sup> person has been correctly created from given JSON string and its attributes were annotation <em>JSONField<\/em> is present were set.<\/p>\n<pre>P1: {\"age\":30,\"name\":\"John\"}\r\nP2: {\"age\":47,\"name\":\"Mike\"}\r\nP3: {\"age\":47,\"name\":\"Mike\"}<\/pre>\n<p>It is also important to say that this example operates with basic class attribute types only. If you&#8217;d like to have more complex objects serialized to\/from JSON then you&#8217;d need to modify this example accordingly \ud83d\ude1b<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article I&#8217;d like to present: Example of Object serialization into JSON string Deserialization of JSON string to the Object<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"Java - JSON serialization","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[9,10],"tags":[254,257,444,259,253,260],"class_list":["post-906","post","type-post","status-publish","format-standard","hentry","category-development","category-java","tag-annotation","tag-isannotationpresent","tag-java","tag-json","tag-reflection","tag-serialization"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3nYbe-eC","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts\/906","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=906"}],"version-history":[{"count":1,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts\/906\/revisions"}],"predecessor-version":[{"id":907,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts\/906\/revisions\/907"}],"wp:attachment":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=906"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=906"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=906"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}