java - Is there any way to convert a Map to a JSON representation using Jackson without writing to a file? -
i'm trying use jackson convert hashmap json representation.
however, ways i've seen involve writing file , reading back, seems inefficient. wondering if there anyway directly?
here's example of instance i'd it
public static party readoneparty(string partyname) { party localparty = new party(); if(connection==null) { connection = new dbconnection(); } try { string query = "select * pureservlet party_name=?"; ps = con.preparestatement(query); ps.setstring(1, partyname); resultset = ps.executequery(); meta = resultset.getmetadata(); string columnname, value; resultset.next(); for(int j=1;j<=meta.getcolumncount();j++) { // necessary start @ j=1 because of mysql index starting @ 1 columnname = meta.getcolumnlabel(j); value = resultset.getstring(columnname); localparty.getpartyinfo().put(columnname, value); // hashmap within party keeps track of individual values. column name = label, value value } } } public class party { hashmap <string,string> partyinfo = new hashmap<string,string>(); public hashmap<string,string> getpartyinfo() throws exception { return partyinfo; } }
the output this
"partyinfo": { "party_name": "vsn", "party_id": "92716518", "party_number": "92716518" }
so far every example i've come across of using objectmapper
involves writing file , reading back.
is there jackson version of java's hashmap
or map
that'll work in similar way have implemented?
pass map objectmapper.writevalueasstring(object value)
it's more efficient using stringwriter
, according docs:
method can used serialize java value string. functionally equivalent calling writevalue(writer,object) stringwriter , constructing string, more efficient.
example
import org.codehaus.jackson.map.objectmapper; import java.io.ioexception; import java.util.hashmap; import java.util.map; public class example { public static void main(string[] args) throws ioexception { map<string,string> map = new hashmap<>(); map.put("key1","value1"); map.put("key2","value2"); string mapasjson = new objectmapper().writevalueasstring(map); system.out.println(mapasjson); } }
Comments
Post a Comment