从单个servlet接收和解释不同类型的JSON对象

时间:2016-10-19 05:20:25

标签: java json

我想从单个URL servlet中获取几种类型的JSON读数。例如,ReadingType1,ReadingType2,ReadingType3 ......每个都有自己的结构。

但是,根据我的代码,当我解析JSON字符串并将其转换为Java对象时,我必须指定要将其强制转换为的对象类型。没有机制来检查JSON的结构,以确定将其强制转换为什么类型的对象。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    StringBuffer sb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (Exception e) {
    }

    Gson gson = new Gson();
    Reading reading = gson.fromJson(sb.toString(), Reading.class);
}

注意最后一行指定在将其转换为对象时类型为“读取”。

在确定JSON输入的对象之前,如何检查JSON输入的结构?

E.g。

if (JSON has structure1) { reading = gson.fromJson(sb.toString(), ReadingType1.class); }

else if (JSON has structure2) { reading = gson.fromJson(sb.toString(), ReadingType2.class); }

else if (JSON has structure3) { reading = gson.fromJson(sb.toString(), ReadingType3.class); }

1 个答案:

答案 0 :(得分:0)

我在我的JSON中添加了一个字符串参数,其中包含了类名。

// sample JSON
{
    "factType":"SomeFact",
    "someParam":"value"
}

package com.acme.services;

import java.io.IOException;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * service that maps JSON to class
 * 
 * @author gal.nitzan.1
 *
 */

@Service
public class MapperService {
    private ObjectMapper mapper = new ObjectMapper();

    public MapperService() {
    }

    @SuppressWarnings("rawtypes")
    public Class mapToClass(String jsonString) throws IllegalFactPayloadException {
        if (jsonString == null || jsonString.length() == 0) {
            throw new IllegalFactPayloadException("jsonString can not be null or empty.");
        }

        Class clazz = null;
        ObjectNode node = null;

        try {
            node = mapper.readValue(jsonString, ObjectNode.class);
        }
        catch (JsonParseException e) {
            throw new IllegalFactPayloadException(e);
        }
        catch (JsonMappingException e) {
            throw new IllegalFactPayloadException(e);
        }
        catch (IOException e) {
            throw new IllegalFactPayloadException(e);
        }

        if (node.has("factType")) {
            try {
                clazz = Class.forName("com.acme.entities." + node.get("factType").asText());
            }
            catch (ClassNotFoundException e) {
                throw new IllegalFactPayloadException(e);
            }
        }
        else {
            throw new IllegalFactPayloadException("jsonString is missing factType attribute.");
        }

        return clazz;
    }
}

HTH, 伽