【问题标题】:How can I convert a Spring MVC JSON view object to a string in Java?如何将 Spring MVC JSON 视图对象转换为 Java 中的字符串?
【发布时间】:2016-01-02 11:02:42
【问题描述】:

这是我的第一篇 Stackoverflow 帖子。我是 Java 新手,可以这么说已经被扔进了池子的深处。

我的公司已经建立了一个大型框架,该框架已经很好地将 ERP 系统上的数据库中的数据提取到 JSON 视图对象中,以用于他们的 Web UI。他们使用 Spring MVC 框架和 MappingJacksonJsonView 类将传入的内容呈现到 JSON 格式的 View 对象中。


我需要以 JSON 格式检索数据,然后将其插入 MongoDB。

理想情况下,我只需调用他们返回 JSON 视图对象的方法并将它们转换为我可以插入到 MongoDB 中的 JSON 字符串。否则,我将拆解他们现有的代码,以尝试在创建视图对象之前模拟他们正在做的事情(这对学习来说不是一件坏事,但很耗时)。

是否有将 Spring MVC 视图对象转换为字符串的直接方法?尽管我发现了一些关于 MVC 和 ASP.net 的类似响应,但我所有的谷歌搜索都没有返回任何有用的信息。我还发现了一个将 hashMap 呈现为 Json 字符串的示例。也许我应该只是寻找一些机制来做到这一点,而不是使用下面的 HashSet?

/*
 Here the data is being retrieved in a certain format from our databases using existing 
 infrastructure and the data gets converted into a View object named view.
*/
ResultSet rs = getBrowseData(newBrowseId, newQueryParameters);

model.addAttribute(MODEL_ATTRIBUTE_DATA, rs);

model.addAttribute(MODEL_ATTRIBUTE_AUX_DATA, rs.getAuxillaryData());


View view = createJsonView(new HashSet<String>(Arrays.asList(MODEL_ATTRIBUTE_AUX_DATA, MODEL_ATTRIBUTE_DATA)));

/*
 Ideally, after that last line, I would just convert the new View object view into a 
 String and pass it into our MongoDB database because all the work formatting the data 
 as Json has been done.
 OR - I could take the HashSet<String> and convert that to a JsonString instead of calling
 the createJsonView method, but I'm only seeing where I can pass in a HashMap to 
 objectmapper if I use org.codehaus.jackson.map.ObjectMapper (as an example). 
 Is there an objectMapper for HashSet? How could I create a HashMap instead of HashSet?
 Otherwise, I'm going to need to do everything the following code does except instead 
 return the code as a string.
*/


public View createJsonView(Set<String> renderedAttributes) {
  MappingJacksonJsonView view = JsonUtil.CreateJsonMapperView(null);
  view.setRenderedAttributes(renderedAttributes);
  return view;
}


/**
* Creates a Json-mapping-view object configured with the specified FilterProvider for controlling serialization 
* of objects from the model to JSON data.
* @param filters Filter provider to specify JSON data filtering. Can be null if no filtering is desired.
* @return Spring View that will return serialized JSON data to client.
*/
public static MappingJacksonJsonView CreateJsonMapperView(FilterProvider filters) {
    MappingJacksonJsonView view = new MappingJacksonJsonView();
    view.setObjectMapper(CreateJsonMapper(filters));

    return view;
    }

/**
* Creates a Json-object-mapper object configured with the specified FilterProvider for controlling serialization 
* of objects to JSON data using filtering (e.g for security by hiding fields).
* @param filters Filter provider to specify JSON data filtering. Can be null if no filtering is desired.
* @return ObjectMapper that can be used to serialize JSON data from objects.
*/
public static ObjectMapper CreateJsonMapper(FilterProvider filters) {
    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.setDateFormat(SerializationUtil.getStandardDateFormat());
    // Ignore any unknown properties received in JSON objects
    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    if (filters != null) {
    // use our own custom filter introspector so that we do not need to pollute our data beans with filter annotations
    JsonFilterIntrospector filterIntrospector = new JsonFilterIntrospector();       
    objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withAnnotationIntrospector(filterIntrospector));

    // apply input filters
    objectMapper.setFilters(filters);
    }

  return objectMapper;
}

【问题讨论】:

  • 你能显示一些JSON view objects 的代码吗?该术语无法自我解释。
  • 帖子已编辑,包括对我正在尝试的内容和包含代码的进一步说明。

标签: java string object view


【解决方案1】:
Use gson.jar to convert json to java object. 

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {

    Gson gson = new Gson();

    try {

        BufferedReader br = new BufferedReader(
            new FileReader("c:\\file.json"));

        //convert the json string back to object
        DataObject obj = gson.fromJson(br, DataObject.class);

        System.out.println(obj);

    } catch (IOException e) {
        e.printStackTrace();
    }

    }
}

【讨论】:

  • 我看了一点 gson,但我的情况有点不同。问题是我在 java 对象、Spring MVC 视图中有 Json 数据,需要将 Json 数据从视图中提取到字符串中。我已经编辑了我的问题以更清楚。谢谢。
  • 改变我对这个问题的看法,看起来我可以通过使用 Gson 将 arrayList 转换为 Json 来获得我需要的东西,方法是执行类似 String jsonResults = Gson().toJson(arraylist) ;但是,当我尝试通过 Spring 将 com.google.gson.Gson 导入我的代码时,它找不到它。它们不兼容吗?
  • @Kurt Ehrler jackson 一直是 springframework 中的默认 json 库,直到 4.1 版它通过配置 GsonHttpMessageConverter 添加了对使用 Gson 的支持。请参阅下面链接中的示例。 leveluplunch.com/java/tutorials/…
猜你喜欢
  • 2019-06-03
  • 1970-01-01
  • 2015-05-24
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 2011-08-30
相关资源
最近更新 更多