Tworzenie tablicy json

0

Chciałbym utworzyć tablice json która będzie wyglądać tak:

 

[
{"title" : "przykład"},
{"title": "przykład1"}
]

Mam taką prostą metodę w której próbuje to uczynić:


public static Map<String, Object> searchDocument(Client client, String index, String type,String field, String value){

			SearchResponse response = client.prepareSearch(index)
			              .setTypes(type)
			              .setSearchType(SearchType.QUERY_AND_FETCH)
			              //.setQuery(fieldQuery(field, value))
			              .setQuery(QueryBuilders.matchAllQuery())
			              .setFrom(0).setSize(10).setExplain(true)
			              .execute()
			              .actionGet();
			
			Map<String, Object> results = new HashMap();
			
			for (SearchHit hit : response.getHits()) {
				Map<String,Object> result = hit.getSource();
				results.put("title", result.get("title"));
				
				System.out.println(result.get("title"));
				System.out.println(result.get("postDate"));
				System.out.println(result.get("author"));
				System.out.println(result.get("title"));
		    }
			return result;

	}

Lecz wartości zostają nadpisywane i dostaje w resultacie takie cos:

 
{
"title" : "przykład1"
}

Co robię nie tak?

0

Uzywasz HashMap-y, a ta nie pozwala na z duplikowane klucze.

Możesz np. zrobić listę map:

	List<Map> result = new ArrayList();
	Map<String, Object> mapObject= new HashMap();
	mapObject.put("title", result.get("title"));
	result.add(mapObject);

lub przesłać tablice wartości dla klucza title (co chyba ma większy sens):

Map<String, ArrayList<String>> result= new HashMap<String, ArrayList>();
//przed wstawieniem elementu sprawdz, czy mapa posiada dany klucz
	ArrayList tempList = null;
	if (result.containsKey(key)) {
  		tempList = result.get(key);
  		if(tempList == null)
	 		tempList = new ArrayList();
  			tempList.add(value);  
		} else {
  			tempList = new ArrayList();
  			tempList.add(value);               
		}
		result.put(key,tempList);
	}

To zwroci JSON w postaci:

{
	"title": ["title1","title2","title3"]
}
0

Pierwszy przykład zwraca mi takie cos:

[
{"title" : "przykład1"},
{"title" : "przykład1"}
]

A w drugi chcialbym uzyskać takie cos:

 
[
{"title" : "przykład"},
{"title" : "przykład1"}
]

a nie :

{
    "title": ["title1","title2","title3"]
}
0

Tylko że jak jadę System.out.println(result.get("title")); np to zwraca poprawne wartości jedna za drugą.

0
package demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.node.Node;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aerospike.client.AerospikeClient;
import com.aerospike.client.Bin;
import com.aerospike.client.Key;
import com.aerospike.client.Record;

import static org.elasticsearch.node.NodeBuilder.*;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
import org.elasticsearch.index.query.QueryBuilders.*;
import org.elasticsearch.index.query.FilterBuilders.*;

@Controller
@RequestMapping("/greeting")
public class Greeting {
	
	@RequestMapping("/index")
	public @ResponseBody List<Map> index() throws IOException{
		Node node = nodeBuilder().clusterName("elasticsearch").node();
		Client client = node.client();
		
		
		client.prepareIndex("kodcucom", "article", "1")
        .setSource(putJsonDocument("ElasticSearch: Java API","ElasticSearch provides the Java API, all operations "+ "can be executed asynchronously using a client object.",
                                   new Date(),
                                   new String[]{"elasticsearch"},
                                   "Hüseyin Akdoğan")).execute().actionGet();
		
		
		client.prepareIndex("kodcucom", "article", "2")
        .setSource(putJsonDocument("ElasticSearch2: Java API","ElasticSearch provides the Java API, all operations2 "+ "can be executed asynchronously using a client 2object.",
                                   new Date(),
                                   new String[]{"elasticsearch2"},
                                   "Hüseyin Akdoğan2")).execute().actionGet();
		
		
		client.prepareIndex("kodcucom", "article", "3")
        .setSource(putJsonDocument("ElasticSearch3: Java API","ElasticSearch provides the Java API, all operations2 "+ "can be executed asynchronously using a client 2object.",
                                   new Date(),
                                   new String[]{"elasticsearch3"},
                                   "Radek")).execute().actionGet();
		
		
		GetResponse getResponse = client.prepareGet("kodcucom", "article", "2").execute().actionGet();

		Map<String, Object> source = getResponse.getSource();
		
		
		return searchDocument(client, "kodcucom", "article", "title", "ElasticSearch");
	}
	
	public static Map<String, Object> putJsonDocument(String title, String content, Date postDate,
            String[] tags, String author){

			Map<String, Object> jsonDocument = new HashMap<String, Object>();
			
			jsonDocument.put("title", title);
			jsonDocument.put("conten", content);
			jsonDocument.put("postDate", postDate);
			jsonDocument.put("tags", tags);
			jsonDocument.put("author", author);
			
			return jsonDocument;
	}
	
	public static List<Map> searchDocument(Client client, String index, String type,String field, String value){

			SearchResponse response = client.prepareSearch(index)
			              .setTypes(type)
			              .setSearchType(SearchType.QUERY_AND_FETCH)
			              .setQuery(QueryBuilders.matchAllQuery())
			              .setFrom(0).setSize(60).setExplain(true)
			              .execute()
			              .actionGet();
			
			
			List<Map> list = new ArrayList();
		    Map<String, Object> mapObject= new HashMap();
		    
			
			Map<String, Object> results = new HashMap();
			
			for (SearchHit hit : response.getHits()) {
				Map<String,Object> result = hit.getSource();
				
				mapObject.put("title", result.get("title"));
				list.add(mapObject);
				
				results.put("title", result.get("title"));
				
//te wartości poprawnie pokazują w konsoli
				System.out.println(result.get("title"));
				System.out.println(result.get("postDate"));
				System.out.println(result.get("author"));
				System.out.println(result.get("tags"));
		    }
			return result;

	}
	
}

1

Przede wszystkim wygląda na to, ze zwracasz nie ten obiekt.
Spróbuj cos takiego:

List<Map> list = new ArrayList();
Map<String, Object> mapObject;
Map<String, Object> results = new HashMap();

for (SearchHit hit : response.getHits()) {
	result = hit.getSource();
	
	mapObject = new HashMap();
	mapObject.put("title", result.get("title"));
	
	list.add(mapObject);

	//te wartości poprawnie pokazują w konsoli
	System.out.println(result.get("title"));
	System.out.println(result.get("postDate"));
	System.out.println(result.get("author"));
	System.out.println(result.get("tags"));
}
return list;
0

Obiekt dobry zwracałem tylko nie te od komentowałem co trzeba :) Ten kod niby działa utworzenie nowej instancji mapObject niby pomogło dzięks tylko pytanie dlaczego za każdym razem trzeba tworzyć ją od nowa?

1 użytkowników online, w tym zalogowanych: 0, gości: 1