Java Object to Json toJson(Object obj)

Here you can find the source of toJson(Object obj)

Description

to Json

License

Open Source License

Declaration

public static String toJson(Object obj) 

Method Source Code

//package com.java2s;
/*// w  w w  . j av a  2 s  .co m
 * Copyright 2014 Jim. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    private static ObjectMapper mapper;

    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String toJSON(int ret) {
        String msg = "Error data!";
        if (ret == 0) {
            msg = "ok";
        }
        return toJSON("null", msg, ret);
    }

    public static String toJSON(String msg, int ret) {
        return toJSON("null", msg, ret);
    }

    /**
     * 
     * @param data
     *            json data
     * @param msg
     *            message
     * @param ret
     *            0--true, not 0--false
     * @return
     */
    public static String toJSON(String data, String msg, int ret) {
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        sb.append("\"data\":");
        sb.append(data);
        sb.append(",\"msg\":\"");
        sb.append(msg);
        sb.append("\",\"ret\":");
        sb.append(ret);
        sb.append('}');
        return sb.toString();
    }
}

Related

  1. toJson(Object message)
  2. toJson(Object o)
  3. toJson(Object o)
  4. toJSON(Object obj)
  5. toJSON(Object obj)
  6. toJson(Object object)
  7. toJson(Object object)
  8. toJson(Object object)
  9. toJson(Object value)