简体   繁体   English

将复杂的Java对象映射到Json数组

[英]Map complex Java Object to Json Array

I have an Ann class that contains a List of Anime. 我有一个包含动漫列表的Ann类。 Anime contains attributes id, name and List of info. 动漫包含属性ID,名称和信息列表。

Ann

package entities;

import javax.xml.bind.annotation.*;
import java.util.*;
import javax.ejb.Stateless;

@Stateless
@XmlRootElement(name = "ann")
public class Ann {

    private List<Anime> Ann = new ArrayList<Anime>();

    @XmlElement(name="anime")
    public List<Anime> getAnn() {
        return Ann;
    }

    public void setAnn(List<Anime> Ann) {
        this.Ann = Ann;
    }

    public Ann() {
        super();
    }}

I want to take Ann (list of anime objects) and parse it into Json to be sent by Gson to an ajax so that the individual elements can ultimately be used/displayed by javascript on my jsp webpage. 我想获取Ann(动漫对象列表)并将其解析为Json,以将Gson发送给ajax,以便最终可以由我的jsp网页上的javascript使用/显示各个元素。

I got it working to some degree with: 我在某种程度上可以使用它:

private void returnResults(HttpServletResponse response, String searchQuery) throws IOException{

  Map <String, String> map = new HashMap<String, String>();

 try{

   for (Anime anime : annj.Unmarshalling(searchQuery).getAnn()) {

     map.put("name", anime.getName());
     map.put("id", anime.getId());

     for (Info temp : anime.getAnime()) {
       if (temp.getSrc() != null) {

         map.put("url", temp.getSrc());

       }
     }

     response.getWriter().write(new Gson().toJson(map));

  }
}catch(Exception e){} 

i send the data to : 我将数据发送到:

$(document).ready(function(){
    $('#searchForm').submit(function(){

        $.ajax({
            url: 'search',
            type: 'POST',
            dataType: 'text',
            data: $('#searchForm').serialize(),
            success: function(data){

//                if(data.isValid){
//                    alert("hi");
                    $('#displaySearchResults').html("Results:" + data);
//                    $('#displaySearchResults').slideDown(500);
//                }
//                else{
//                    alert('Enter a valid search term.');
//                }
            }
        });
        return false;
    });
});

this produces: 这将产生:

Results:{"name":"Neon Genesis Evangelion: The End of Evangelion","id":"419","url":"http://cdn.animenewsnetwork.com/thumbnails/fit200x200/encyc/A419-28.jpg"}{"name":"Neon Genesis Evangelion: Death \u0026 Rebirth","id":"418","url":"http://cdn.animenewsnetwork.com/thumbnails/fit200x200/encyc/A418-12.jpg"}{"name":"Neon Genesis Evangelion","id":"49","url":"http://cdn.animenewsnetwork.com/thumbnails/fit200x200/encyc/A49-16.jpg"}

this is great but it isn't proper JSON format is it? 这很好,但是不是正确的JSON格式吗? shouldn't there be a comma inbetween each entry? 每个条目之间不应该有逗号吗?

i am doing this because i read that you need your data to be in JSON format to display it on a webpage using javascript/jquery. 我这样做是因为我读到您需要数据为JSON格式才能使用javascript / jquery在网页上显示。

ultimately i want to be able to take this search result data and display to the user with a jquery style manipulatable list in picture format. 最终,我希望能够获取此搜索结果数据,并以图片格式的可操作的jquery样式列表向用户显示。

my question is, can you help me figure out how to format the data into a single , correct JSON string? 我的问题是,您能帮我弄清楚如何将数据格式化为单个正确的JSON字符串吗?

I have spent the last hour looking into adding a toString() method on my Ann class to try to return it's attributes directly instead of accessing the individual Anime attributes, something like this 我花了最后一个小时研究在我的Ann类上添加toString()方法,以尝试直接返回其属性,而不是访问各个Anime属性,就像这样

Ann class 安班

//    @Override
//    public String toString(){
//        
//        String masterList = ""; 
//        
//        for (Anime ann : this.Ann){
//        
//           masterList = masterList +  ann.getName();
//            
//        }
//        return masterList;
//    }

Servlet method Servlet方法

//        try{
//            String ann1 = annj.Unmarshalling(searchQuery).getAnn().toString(); 
//            
//            map.put("hi", ann1);
//            
//            response.getWriter().write(new Gson().toJson(map));
//            
//        }catch(Exception e){} 

This didn't seem to access the object data properly and I aborted it since I could be going down that alleyway forever and its probably unnecessary. 这似乎无法正确访问对象数据,并且我中止了它,因为我可能永远走在那条小巷上,这可能是不必要的。 (on 2nd thoughts it looks pretty decent.... but I don't know) (根据第二种想法,它看起来还不错。...但我不知道)

Thankyou for reading. 谢谢您的阅读。

You are tying to print Map object again and again over response; 您打算一次又一次地响应响应打印Map对象。 thats reason you are seeing maps printed without comma. 这就是为什么您看到的地图没有逗号打印。 Put map objects inside ArrayList and print it. 将地图对象放入ArrayList并打印。 it should work. 它应该工作。

private void returnResults(HttpServletResponse response, String searchQuery) throws IOException{

  //arraylist to hold your Mapped String values.
  ArrayList<Map> arrayOfMap = new ArrayList<Map>(); 
 try{

for (Anime anime : annj.Unmarshalling(searchQuery).getAnn()) {
        Map <String, String> map = new HashMap<String, String>();
        map.put("name", anime.getName());
                map.put("id", anime.getId());

                for (Info temp : anime.getAnime()) {
                    if (temp.getSrc() != null) {

 map.put("url", temp.getSrc());

    }
                }

         //add map to arrayList
         arrayOfMap.add(map);


  }
  //once ready, print all arraylist on response
  response.getWriter().write(new Gson().toJson(arrayOfMap));

  }catch(Exception e){} 

Once you have result at client side you can iterate over JSON to get your data printed on page; 在客户端获得结果后,就可以遍历JSON以将数据打印在页面上;

$.each(data.result, function(listID, mapData){
     /* I am assuming you will create Lable for each String in JSON inside your HTML */
    $("#displaySearchResults > idLable").text(mapDate.id);
    $("#displaySearchResults > nameLable").text(mapDate.name);
    $("#displaySearchResults > urlLable").text(mapDate.url);

}

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

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