简体   繁体   English

如何在Java中将Spring MVC JSON视图对象转换为字符串?

[英]How can I convert a Spring MVC JSON view object to a string in Java?

This is my first Stackoverflow post. 这是我的第一个Stackoverflow帖子。 I'm new to Java and have been thrown into the deep end of the pool so to speak. 我是Java的新手,可以这么说。

My company has set up a big framework that is already working well extracting data from databases on an ERP system into JSON view objects to be used for their Web UI. 我公司已经建立了一个大型框架,该框架已经很好地运行,可以将ERP系统上数据库中的数据提取到JSON视图对象中以用于其Web UI。 They are using the Spring MVC framework and the MappingJacksonJsonView Class to render what they are passing in into JSON formatted View objects. 他们正在使用Spring MVC框架和MappingJacksonJsonView类来呈现将它们传递到JSON格式的View对象中。


I need to retrieve the data in JSON format and instead insert it into MongoDB. 我需要以JSON格式检索数据,而不是将其插入MongoDB。

Ideally I'd just call their methods that are returning the JSON View objects and convert them into JSON Strings that I can then insert into MongoDB. 理想情况下,我只调用返回JSON View对象的方法,并将它们转换为JSON字符串,然后将其插入MongoDB。 Otherwise I'm disassembling their existing code to try to emulate what they are doing just prior to creating the view object (not a bad thing for learning, but time consuming). 否则,我将分解他们现有的代码,以尝试模拟他们在创建视图对象之前所做的事情(这对学习不是一件坏事,但很耗时)。

Is there a straight forward way to convert a Spring MVC View object to a String? 是否有直接方法将Spring MVC View对象转换为String? All my google searches are returning nothing useful, although I've found a handful of similar responses regarding MVC and ASP.net. 我的所有Google搜索都没有返回任何有用的信息,尽管我发现了一些关于MVC和ASP.net的类似响应。 I also found an example of rendering a hashMap as a Json string. 我还找到了一个将hashMap呈现为Json字符串的示例。 Maybe I should be just looking for some mechanism to do that instead using the HashSet below? 也许我应该只是在寻找某种机制来代替使用下面的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;
}
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();
    }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM