JSONValue.java

  1. package org.drip.json.simple;

  2. /*
  3.  * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  4.  */

  5. /*!
  6.  * Copyright (C) 2020 Lakshmi Krishnamurthy
  7.  * Copyright (C) 2019 Lakshmi Krishnamurthy
  8.  * Copyright (C) 2018 Lakshmi Krishnamurthy
  9.  * Copyright (C) 2017 Lakshmi Krishnamurthy
  10.  * Copyright (C) 2016 Lakshmi Krishnamurthy
  11.  * Copyright (C) 2015 Lakshmi Krishnamurthy
  12.  *
  13.  *  This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics,
  14.  *      asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment
  15.  *      analytics, and portfolio construction analytics within and across fixed income, credit, commodity,
  16.  *      equity, FX, and structured products. It also includes auxiliary libraries for algorithm support,
  17.  *      numerical analysis, numerical optimization, spline builder, model validation, statistical learning,
  18.  *      and computational support.
  19.  *  
  20.  *      https://lakshmidrip.github.io/DROP/
  21.  *  
  22.  *  DROP is composed of three modules:
  23.  *  
  24.  *  - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/
  25.  *  - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/
  26.  *  - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/
  27.  *
  28.  *  DROP Product Core implements libraries for the following:
  29.  *  - Fixed Income Analytics
  30.  *  - Loan Analytics
  31.  *  - Transaction Cost Analytics
  32.  *
  33.  *  DROP Portfolio Core implements libraries for the following:
  34.  *  - Asset Allocation Analytics
  35.  *  - Asset Liability Management Analytics
  36.  *  - Capital Estimation Analytics
  37.  *  - Exposure Analytics
  38.  *  - Margin Analytics
  39.  *  - XVA Analytics
  40.  *
  41.  *  DROP Computational Core implements libraries for the following:
  42.  *  - Algorithm Support
  43.  *  - Computation Support
  44.  *  - Function Analysis
  45.  *  - Model Validation
  46.  *  - Numerical Analysis
  47.  *  - Numerical Optimizer
  48.  *  - Spline Builder
  49.  *  - Statistical Learning
  50.  *
  51.  *  Documentation for DROP is Spread Over:
  52.  *
  53.  *  - Main                     => https://lakshmidrip.github.io/DROP/
  54.  *  - Wiki                     => https://github.com/lakshmiDRIP/DROP/wiki
  55.  *  - GitHub                   => https://github.com/lakshmiDRIP/DROP
  56.  *  - Repo Layout Taxonomy     => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md
  57.  *  - Javadoc                  => https://lakshmidrip.github.io/DROP/Javadoc/index.html
  58.  *  - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
  59.  *  - Release Versions         => https://lakshmidrip.github.io/DROP/version.html
  60.  *  - Community Credits        => https://lakshmidrip.github.io/DROP/credits.html
  61.  *  - Issues Catalog           => https://github.com/lakshmiDRIP/DROP/issues
  62.  *  - JUnit                    => https://lakshmidrip.github.io/DROP/junit/index.html
  63.  *  - Jacoco                   => https://lakshmidrip.github.io/DROP/jacoco/index.html
  64.  *
  65.  *  Licensed under the Apache License, Version 2.0 (the "License");
  66.  *      you may not use this file except in compliance with the License.
  67.  *  
  68.  *  You may obtain a copy of the License at
  69.  *      http://www.apache.org/licenses/LICENSE-2.0
  70.  *  
  71.  *  Unless required by applicable law or agreed to in writing, software
  72.  *      distributed under the License is distributed on an "AS IS" BASIS,
  73.  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  74.  *  
  75.  *  See the License for the specific language governing permissions and
  76.  *      limitations under the License.
  77.  */

  78. /**
  79.  * <i>JSONValue</i> is an Adaptation of the JSONValue Class from the RFC4627 compliant JSON Simple
  80.  * (https://code.google.com/p/json-simple/).
  81.  *
  82.  *  <br><br>
  83.  *  <ul>
  84.  *      <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li>
  85.  *      <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationSupportLibrary.md">Computation Support</a></li>
  86.  *      <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/json">RFC-4627 Compliant JSON Encoder/Decoder (Parser)</a></li>
  87.  *      <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/json/simple">RFC4627 Compliant JSON Message Object</a></li>
  88.  *  </ul>
  89.  *
  90.  * @author Fang Yidong
  91.  * @author Lakshmi Krishnamurthy
  92.  */

  93. public class JSONValue {
  94.     /**
  95.      * Parse JSON text into java object from the input source.
  96.      * Please use parseWithException() if you don't want to ignore the exception.
  97.      *
  98.      * @see org.drip.json.parser.JSONParser#parse(Reader)
  99.      * @see #parseWithException(Reader)
  100.      *
  101.      * @param in Input Reader
  102.      *
  103.      * @return Instance of the following:
  104.      *      org.drip.json.simple.JSONObject,
  105.      *      org.drip.json.simple.JSONArray,
  106.      *      java.lang.String,
  107.      *      java.lang.Number,
  108.      *      java.lang.Boolean,
  109.      *      null
  110.      *
  111.      */
  112.     public static Object parse(java.io.Reader in){
  113.             try{
  114.                     org.drip.json.parser.JSONParser parser=new org.drip.json.parser.JSONParser();
  115.                     return parser.parse(in);
  116.             }
  117.             catch(Exception e){
  118.                     return null;
  119.             }
  120.     }
  121.    
  122.     public static Object parse(String s){
  123.         java.io.StringReader in=new java.io.StringReader(s);
  124.             return parse(in);
  125.     }
  126.    
  127.     /**
  128.      * Parse JSON text into java object from the input source.
  129.      *
  130.      * @see org.drip.json.parser.JSONParser
  131.      *
  132.      * @param in Input Reader
  133.      * @return Instance of the following:
  134.      *      org.json.simple.JSONObject,
  135.      *      org.json.simple.JSONArray,
  136.      *      java.lang.String,
  137.      *      java.lang.Number,
  138.      *      java.lang.Boolean,
  139.      *      null
  140.      *
  141.      * @throws java.io.IOException Thrown if the Inputs are Invalid
  142.      *
  143.      * @throws org.drip.json.parser.ParseException Thrown if the Inputs are Invalid
  144.      */
  145.     public static Object parseWithException(java.io.Reader in) throws java.io.IOException, org.drip.json.parser.ParseException{
  146.         org.drip.json.parser.JSONParser parser=new org.drip.json.parser.JSONParser();
  147.             return parser.parse(in);
  148.     }
  149.    
  150.     public static Object parseWithException(String s) throws org.drip.json.parser.ParseException{
  151.         org.drip.json.parser.JSONParser parser=new org.drip.json.parser.JSONParser();
  152.             return parser.parse(s);
  153.     }
  154.    
  155. /**
  156.  * Encode an object into JSON text and write it to out.
  157.  * <p>
  158.  * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
  159.  * <p>
  160.  * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
  161.  * "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
  162.  *
  163.  * @see org.drip.json.simple.JSONObject#writeJSONString(Map, Writer)
  164.  * @see org.drip.json.simple.JSONArray#writeJSONString(List, Writer)
  165.  *
  166.  * @param value The JSON Object
  167.  * @param out The JSON Writer
  168.  *
  169.  * @throws java.io.IOException Thrown if the Inputs are Invalid
  170.  */
  171.     @SuppressWarnings ("rawtypes") public static void writeJSONString(Object value, java.io.Writer out) throws java.io.IOException {
  172.             if(value == null){
  173.                     out.write("null");
  174.                     return;
  175.             }
  176.            
  177.             if(value instanceof String){            
  178.         out.write('\"');
  179.                     out.write(escape((String)value));
  180.         out.write('\"');
  181.                     return;
  182.             }
  183.            
  184.             if(value instanceof Double){
  185.                     if(((Double)value).isInfinite() || ((Double)value).isNaN())
  186.                             out.write("null");
  187.                     else
  188.                             out.write(value.toString());
  189.                     return;
  190.             }
  191.            
  192.             if(value instanceof Float){
  193.                     if(((Float)value).isInfinite() || ((Float)value).isNaN())
  194.                             out.write("null");
  195.                     else
  196.                             out.write(value.toString());
  197.                     return;
  198.             }              
  199.            
  200.             if(value instanceof Number){
  201.                     out.write(value.toString());
  202.                     return;
  203.             }
  204.            
  205.             if(value instanceof Boolean){
  206.                     out.write(value.toString());
  207.                     return;
  208.             }
  209.            
  210.             if((value instanceof JSONStreamAware)){
  211.                     ((JSONStreamAware)value).writeJSONString(out);
  212.                     return;
  213.             }
  214.            
  215.             if((value instanceof JSONAware)){
  216.                     out.write(((JSONAware)value).toJSONString());
  217.                     return;
  218.             }
  219.            
  220.             if(value instanceof java.util.Map){
  221.                 org.drip.json.simple.JSONObject.writeJSONString((java.util.Map)value, out);
  222.                     return;
  223.             }
  224.            
  225.             if(value instanceof java.util.List){
  226.                     JSONArray.writeJSONString((java.util.List)value, out);
  227.         return;
  228.             }
  229.            
  230.             out.write(value.toString());
  231.     }

  232.     /**
  233.      * Convert an object to JSON text.
  234.      * <p>
  235.      * If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly.
  236.      * <p>
  237.      * DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with
  238.      * "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead.
  239.      *
  240.      * @see org.drip.json.simple.JSONObject#toJSONString(Map)
  241.      * @see org.drip.json.simple.JSONArray#toJSONString(List)
  242.      *
  243.      * @param value The JSON Object
  244.      *
  245.      * @return JSON text, or "null" if value is null or it's an NaN or an INF number.
  246.      */

  247.     @SuppressWarnings ("rawtypes") public static String toJSONString(Object value){
  248.             if(value == null)
  249.                     return "null";
  250.            
  251.             if(value instanceof String)
  252.                     return "\""+escape((String)value)+"\"";
  253.            
  254.             if(value instanceof Double){
  255.                     if(((Double)value).isInfinite() || ((Double)value).isNaN())
  256.                             return "null";
  257.                     else
  258.                             return value.toString();
  259.             }
  260.            
  261.             if(value instanceof Float){
  262.                     if(((Float)value).isInfinite() || ((Float)value).isNaN())
  263.                             return "null";
  264.                     else
  265.                             return value.toString();
  266.             }              
  267.            
  268.             if(value instanceof Number)
  269.                     return value.toString();
  270.            
  271.             if(value instanceof Boolean)
  272.                     return value.toString();
  273.            
  274.             if((value instanceof JSONAware))
  275.                     return ((JSONAware)value).toJSONString();
  276.            
  277.             if(value instanceof java.util.Map)
  278.                     return org.drip.json.simple.JSONObject.toJSONString((java.util.Map)value);
  279.            
  280.             if(value instanceof java.util.List)
  281.                     return org.drip.json.simple.JSONArray.toJSONString((java.util.List)value);
  282.            
  283.             return value.toString();
  284.     }

  285.     /**
  286.      * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
  287.      *
  288.      * @param s Pre-escape String
  289.      *
  290.      * @return The Escape String
  291.      */
  292.     public static String escape(String s){
  293.             if(s==null)
  294.                     return null;
  295.     StringBuffer sb = new StringBuffer();
  296.     escape(s, sb);
  297.     return sb.toString();
  298. }

  299. /**
  300.  * @param s - Must not be null.
  301.  * @param sb The StringBuffer
  302.  */
  303. static void escape(String s, StringBuffer sb) {
  304.             for(int i=0;i<s.length();i++){
  305.                     char ch=s.charAt(i);
  306.                     switch(ch){
  307.                     case '"':
  308.                             sb.append("\\\"");
  309.                             break;
  310.                     case '\\':
  311.                             sb.append("\\\\");
  312.                             break;
  313.                     case '\b':
  314.                             sb.append("\\b");
  315.                             break;
  316.                     case '\f':
  317.                             sb.append("\\f");
  318.                             break;
  319.                     case '\n':
  320.                             sb.append("\\n");
  321.                             break;
  322.                     case '\r':
  323.                             sb.append("\\r");
  324.                             break;
  325.                     case '\t':
  326.                             sb.append("\\t");
  327.                             break;
  328.                     case '/':
  329.                             sb.append("\\/");
  330.                             break;
  331.                     default:
  332.             //Reference: http://www.unicode.org/versions/Unicode5.1.0/
  333.                             if((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){
  334.                                     String ss=Integer.toHexString(ch);
  335.                                     sb.append("\\u");
  336.                                     for(int k=0;k<4-ss.length();k++){
  337.                                             sb.append('0');
  338.                                     }
  339.                                     sb.append(ss.toUpperCase());
  340.                             }
  341.                             else{
  342.                                     sb.append(ch);
  343.                             }
  344.                     }
  345.             }//for
  346.     }
  347. }