how to convert object to string in java - java

I have a function that returns map value (String) as a generic Object. How do I convert it back to string. I tried toString() but all i get is end[Ljava.lang.String;#ff2413
public Object getParameterValue(String key)
{
Iterator iterator=params.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry me=(Map.Entry)iterator.next();
String[] arr=(String[])me.getValue();
log.info(me.getKey().toString()+"="+arr[0]);
}
if(params.containsKey(key))
{
log.info(key+"="+params.get(key));
return params.get(key);
}
return null;
}
Receiving end
String temp=data.getParameterValue("request").toString();
log.info("end"+temp);
log.info(me.getKey().toString()+"="+arr[0]); give me an output
email=x#as.com
request=login
projectid=as

I'm afraid your map contains something other than String objects. If you call toString() on a String object, you obtain the string itself.
What you get [Ljava.lang.String indicates you might have a String array.

Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand
package pt.iol.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
public class ObjectUtil {
static final Base64 base64 = new Base64();
public static String serializeObjectToString(Object object) throws IOException {
try (
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
return new String(base64.encode(arrayOutputStream.toByteArray()));
}
}
public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
try (
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
return objectInputStream.readObject();
}
}
}

maybe you benefit from converting it to JSON string
String jsonString = new com.google.gson.Gson().toJson(myObject);
in my case, I wanted to add an object to the response headers but you cant add objects to the headers,
so to solve this I convert my object to JSON string and in the client side I will return that string to JSON again

Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.

The result is not a String but a String[]. That's why you get this unsuspected printout.
[Ljava.lang.String is a signature of an array of String:
System.out.println(new String[]{});

The question how do I convert an object to a String, despite the several answers you see here, and despite the existence of the Object.toString method, is unanswerable, or has infinitely many answers. Because what is being asked for is some kind of text representation or description of the object, and there are infinitely many possible representations. Each representation encodes a particular object instance using a special purpose language (probably a very limited language) or format that is expressive enough to encode all possible object instances.
Before code can be written to convert an object to a String, you must decide on the language/format to be used.

To convert serialize object to String and String to Object
stringToBean(beanToString(new LoginMdp()), LoginMdp.class);
public static String beanToString(Object object) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
StringWriter stringEmp = new StringWriter();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.writeValue(stringEmp, object);
return stringEmp.toString();
}
public static <T> T stringToBean(String content, Class<T> valueType) throws IOException {
return new ObjectMapper().readValue(content, valueType);
}

Solution 1: cast
String temp=(String)data.getParameterValue("request");
Solution 2: use typed map:
Map<String, String> param;
So you change Change the return type of your function
public String getParameterValue(String key)
{
if(params.containsKey(key))
{
return params.get(key);
}
return null;
}
and then no need for cast or toString
String temp=data.getParameterValue("request");

toString() is a debug info string. The default implementation returns the class name and the system identity hash. Collections return all elements but arrays not.
Also be aware of NullPointerException creating the log!
In this case a Arrays.toString() may help:
Object temp = data.getParameterValue("request");
String log = temp == null ? "null" : (temp.getClass().isArray() ? Arrays.toString((Object[])temp) : temp.toString());
log.info("end " + temp);
You can also use Arrays.asList():
Object temp = data.getParameterValue("request");
Object log = temp == null ? null : (temp.getClass().isArray() ? Arrays.asList((Object[])temp) : temp);
log.info("end " + temp);
This may result in a ClassCastException for primitive arrays (int[], ...).

/** * This toString-Method works for every Class, where you want to display all the fields and its values */ public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString(); }

You can create toString() method to convert object to string.
int bid;
String bname;
double bprice;
Book(String str)
{
String[] s1 = str.split("-");
bid = Integer.parseInt(s1[0]);
bname = s1[1];
bprice = Double.parseDouble(s1[2]);
}
public String toString()
{
return bid+"-"+bname+"-"+bprice;
}
public static void main(String[] s)
{
Book b1 = new Book("12-JAVA-200.50");
System.out.println(b1);
}

Related

How to convert object to query string in Java?

I am trying to convert the following object to query string, so that can be used with GET request.
Class A {
String prop1;
String prop2;
Date date1;
Date date2;
ClassB objB;
}
Class B {
String prop3;
String prop4;
}
We can do that first object to Map then convert map to MultiValueMap and use URIComponentsBuilder.fromHttpUrl("httpL//example.com").queryParams(multiValueMap).build();
Is there shorter and better way of converting object to query string so that be used with GET request in Spring Project for Junit Test?
Why convert to Map then MultiValueMap, instead of just building it directly?
DateFormat dateFmt = new SimpleDateFormat("whatever date format you want");
URIComponentsBuilder.fromHttpUrl("httpL//example.com")
.queryParam("prop1", a.prop1)
.queryParam("prop2", a.prop2)
.queryParam("date1", dateFmt.format(a.date1))
.queryParam("date2", dateFmt.format(a.date2))
.queryParam("prop3", a.objB.prop3)
.queryParam("prop4", a.objB.prop4)
.build();
You could write your own method that uses java.lang.reflect. Here's an example
public static String getRequestString(String urlString, Class clazz, Object o){
String queryString = "?";
try {
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
queryString += queryString.concat(f.getName() + "=" + String.valueOf(f.get(o)) + "&");
}
}catch (Exception e){
e.printStackTrace();
}
return urlString + queryString.substring(0,queryString.length()-1);
}
OpenFeign has the annotation #QueryMap to generate query params dinamicaly based on a object attributes:
public interface Api {
#RequestLine("GET /find")
V find(#QueryMap CustomPojo customPojo);
}
See more at:
https://github.com/OpenFeign/feign#dynamic-query-parameters
This is how i would do it,
Create Map, populate and then iterate over map items and append to builder this seems to be working for me. It does not cover support for nested objects. Should be simple with recursion.
public String getRequestString(Class clazz, Object o) {
StringBuilder queryStringBuilder = new StringBuilder();
final Map<String, String> queryParams = new LinkedHashMap<>();
try {
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
queryParams.put(f.getName(), String.valueOf(f.get(o)));
}
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
queryStringBuilder.append(testStringUtils.toSnakeCase(entry.getKey()));
queryStringBuilder.append("=");
queryStringBuilder.append(entry.getValue());
queryStringBuilder.append("&");
}
logger.info("Map: " + queryParams);
} catch (Exception e) {
e.printStackTrace();
}
final String queryString = queryStringBuilder.toString();
logger.info("Query string : " + queryString.substring(0, queryString.length() - 1));
return "?" + queryString.substring(0, queryString.length() - 1);

get a variable from constructor

I used this code to verify a digital sign of a file, the constructor prints the context of the file but I wanted to know how to save the print as a variable , since a constructor uses only to "build" objects, this is the code:
public class VerifyMessage {
private List<byte[]> list;
#SuppressWarnings("unchecked")
// The constructor of VerifyMessage class retrieves the byte arrays from the File and prints the message only if the signature is verified.
public VerifyMessage(String filename, String keyFile) throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
this.list = (List<byte[]>) in.readObject();
in.close();
System.out.println(verifySignature(list.get(0), list.get(1), keyFile) ? "VERIFIED MESSAGE" + "\n----------------\n" + new String(list.get(0)) : "Could not verify the signature.");
}
How can I "save" the System.out.println as a global member String variable outside of the constructor?
thanks ahead
Your class already contains a list field.
Similar to that, you declare a string field- and then you simply assign the value you are currently printing to that field.
public class VerifyMessage {
private List<byte[]> list;
Object variable = null;
public VerifyMessage(String filename, String keyFile) throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
this.list = (List<byte[]>) in.readObject();
in.close();
this.variable = this.verifySignature(list.get(0), list.get(1), keyFile);
}
private Object verifySignature(byte[] bs, byte[] bs2, String keyFile) {
//
return null;
}
}

Cut too long strings in json using gson

I would like to cut too long strings in json.
In order to do that I would like to register new type adapter for String type and inside this deserializer I will check and limit too long strings.
Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new CuttingStringDeserializer()).create();
JsonElement element = gson.fromJson(jsonString, JsonElement.class);
return new GsonBuilder().setPrettyPrinting().create().toJson(element);
Example of json file that I want to process:
{
"myString": "this string is too long - cut it",
"other": "this is ok"
}
Desired output:
{
"myString": "this strin",
"other": "this is ok"
}
In general I don't know structure of json but I want to filter all string occurrences.
Deserializer:
public class CuttingStringDeserializer implements JsonDeserializer<String> {
#Override
public String deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
String s = json.getAsString();
if(s.lenght() > MAX_CONTENT_LENGTH){
return s.substring(0, MAX_CONTENT_LENGTH);
}else{
return s;
}
}
Unfortunately my custom deserializer is not called by gson.
This (using some custom JsonWriter) works:
package so41793888;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.stream.JsonWriter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.io.StringWriter;
public class Demo {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"myString\": \"this string is too long - cut it\",\n" +
" \"other\": \"this is ok\"\n" +
"}";
Gson gson = new GsonBuilder().create();
JsonElement element = gson.fromJson(jsonString, JsonElement.class);
StringWriter out = null;
try {
out = new StringWriter();
new GsonBuilder().create().toJson(element, new MyJsonWriter(out));
System.out.println(out.getBuffer().toString());
} finally {
IOUtils.closeQuietly(out);
}
}
private static class MyJsonWriter extends JsonWriter {
public MyJsonWriter(final StringWriter out) {
super(out);
setIndent(" ");
}
#Override
public JsonWriter value(final String value) throws IOException {
return super.value(StringUtils.abbreviate(value, 12));
}
}
}
outputs:
{
"myString": "this stri...",
"other": "this is ok"
}
You can reject the idea of tree processing (the way how JsonSerializer and JsonDeserializer work) in favor of stream processing, where you analyze every token on your own. GsonBuilder seems not to allow overriding a streaming-fashioned TypeAdapters as well, but you can then use JsonReader in order to parse every token from an input stream, and JsonWriter to emit processed tokens to an output stream. This may look too low level, but since it's a streaming way, it is really cheap and does not consume much memory as tree processing usually does. Thus you can process even infinite streams.
#SuppressWarnings("resource")
private static void trim(final int maxStringLength, final Reader reader, final Writer writer)
throws IOException {
// a specifically configured IDEA complains for the unclosed jsonReader, but invoking the `close` method is a like a chain and sometimes undesirable
#SuppressWarnings("all")
final JsonReader jsonReader = new JsonReader(reader);
// the same goes to jsonWriter
#SuppressWarnings("all")
final JsonWriter jsonWriter = new JsonWriter(writer);
for ( JsonToken token; (token = jsonReader.peek()) != END_DOCUMENT; ) {
switch ( token ) {
case BEGIN_ARRAY:
// merely reflect a BEGIN_ARRAY token
jsonReader.beginArray();
jsonWriter.beginArray();
break;
case END_ARRAY:
// merely reflect an END_ARRAY token
jsonReader.endArray();
jsonWriter.endArray();
break;
case BEGIN_OBJECT:
// merely reflect a BEGIN_OBJECT token
jsonReader.beginObject();
jsonWriter.beginObject();
break;
case END_OBJECT:
// merely reflect an END_OBJECT token
jsonReader.endObject();
jsonWriter.endObject();
break;
case NAME:
// merely reflect NAME tokens (or trim?)
jsonWriter.name(jsonReader.nextName());
break;
case STRING:
// trimming a STRING token if necessary
final String string = jsonReader.nextString();
jsonWriter.value(string.length() > maxStringLength ? string.substring(0, maxStringLength) : string);
break;
case NUMBER:
// NUMBER tokens are a bit complex because JSON only denotes a double number that can be literally an integer
final String rawNumber = jsonReader.nextString();
try {
// try to write the biggest integer number supported by Java, floating points also fail to be parsed as long values
jsonWriter.value(parseLong(rawNumber));
} catch ( final NumberFormatException nex1 ) {
try {
// not a long value, then perhaps it's a double value?
jsonWriter.value(parseDouble(rawNumber));
} catch ( final NumberFormatException nex2 ) {
// can't think of specific cases here...
throw new AssertionError("Must not happen", nex2);
}
}
break;
case BOOLEAN:
// merely reflect BOOLEAN tokens
jsonWriter.value(jsonReader.nextBoolean());
break;
case NULL:
// merely reflect NULL tokens
jsonReader.nextNull();
jsonWriter.nullValue();
break;
case END_DOCUMENT:
// fall through, because this type of tokens is checked above, and it's fine to throw an assertion error
default:
throw new AssertionError(token);
}
}
}
This method, of course, does not support pretty printing, but it can be easily implemented if it's really necessary.
And how it's used:
final Reader reader = new StringReader("{\"myString\":\"this string is too long - cut it\",\"other\":\"this is ok\"}");
final Writer writer = new OutputStreamWriter(System.out); // redirect the output to System.out
trim(10, reader, writer);
writer.flush(); // flushing at a call-site, we decide
The output:
{"myString":"this strin","other":"this is ok"}
The solution can work with any kind of JSON, having no background for a particular type. Simply speaking, it's just type-unaware and can process even simple single literals like "foo-bar-baz-qux".
It seems for me it doesn't make sense what are you trying to archive, but here kick off code which should help .
public class Main {
private static String json = "{\"myString\": \"this string is too long - limit it\",\"other\": \"this is ok\"}";
public static void main(String... var) {
System.out.print(cutJson(json));
}
public static String cutJson(String json) {
Type type = new TypeToken<Map<String, String>>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(type, new CuttingStringDeserializer()).create();
Map<String, String> element = gson.fromJson(json, type);
return new GsonBuilder().setPrettyPrinting().create().toJson(element);
}
private static class CuttingStringDeserializer implements JsonDeserializer<Map<String, String>> {
#Override
public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Iterator<Map.Entry<String, JsonElement>> iterator = ((JsonObject) json).entrySet().iterator();
Map<String, String> result = new HashMap<String, String>();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
if (entry.getValue().getAsString().length() > 10) {
entry.setValue(new JsonPrimitive(entry.getValue().getAsString().substring(0, 9)));
}
result.put(entry.getKey(), entry.getValue().getAsString());
}
return result;
}
}
}
Prints:
{
"myString": "this stri",
"other": "this is ok"
}

How to encapsulate the logic of parametrized messages?

I'm using java.util.resourcebundle to format my JSTL messages and this works fine:
I use the class MessageFormat you can see here. Now I want to encapsulate this to a method that is just getParametrizedMessage(String key, String[]parameters) but I'm not sure how to do it. Now there is quite a lot of work to display just one or two messages with parameters:
UserMessage um = null;
ResourceBundle messages = ResourceBundle.getBundle("messages");
String str = messages.getString("PF1");
Object[] messageArguments = new String[]{nyreg.getNummer()};
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString("PI14"));
String outputPI14 = formatter.format(messageArguments);
formatter.applyPattern(messages.getString("PI15"));
String outputPI15 = formatter.format(messageArguments)
if(ipeaSisFlag)
if(checkIfPCTExistInDB && nyreg.isExistInDB()) {
//um = new ExtendedUserMessage(MessageHandler.getParameterizedMessage("PI15", new String[]{nyreg.getNummer()}) , UserMessage.TYPE_INFORMATION, "Info");
um = new ExtendedUserMessage(outputPI15 , UserMessage.TYPE_INFORMATION, "Info");
…and so on. Now can I move this logic to a static class MessageHandler.getParameterizedMessage that now is not working and looking like this:
private final static String dictionaryFileName="messages.properties";
public static String getParameterizedMessage(String key, String [] params){
if (dictionary==null){
loadDictionary();
}
return getParameterizedMessage(dictionary,key,params);
}
private static void loadDictionary(){
String fileName = dictionaryFileName;
try {
dictionary=new Properties();
InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);
dictionary.load(fileInput);
fileInput.close();
}
catch(Exception e) {
System.err.println("Exception reading propertiesfile in init "+e);
e.printStackTrace();
dictionary=null;
}
}
How can I make using my parametrized messages as easy as calling a method with key and parameter?
Thanks for any help
Update
The logic comes from an inherited method that in in the abstract class that this extends. The method looks like:
protected static String getParameterizedMessage(Properties dictionary,String key,String []params){
if (dictionary==null){
return "ERROR";
}
String msg = dictionary.getProperty(key);
if (msg==null){
return "?!Meddelande " +key + " saknas!?";
}
if (params==null){
return msg;
}
StringBuffer buff = new StringBuffer(msg);
for (int i=0;i<params.length;i++){
String placeHolder = "<<"+(i+1)+">>";
if (buff.indexOf(placeHolder)!=-1){
replace(buff,placeHolder,params[i]);
}
else {
remove(buff,placeHolder);
}
}
return buff.toString();
}
I think I must rewrite the above method in order to make it work like a resourcebundle rather than just a dictionary.
Update 2
The code that seems to work is here
public static String getParameterizedMessage(String key, Object [] params){
ResourceBundle messages = ResourceBundle.getBundle("messages");
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString(key));
return formatter.format(params);
}
I'm not really sure what you're trying to achive, here's what I did in the past:
public static final String localize(final Locale locale, final String key, final Object... param) {
final String name = "message";
final ResourceBundle rb;
/* Resource bundles are cached internally,
never saw a need to implement another caching level
*/
try {
rb = ResourceBundle.getBundle(name, locale, Thread.currentThread()
.getContextClassLoader());
} catch (MissingResourceException e) {
throw new RuntimeException("Bundle not found:" + name);
}
String keyValue = null;
try {
keyValue = rb.getString(key);
} catch (MissingResourceException e) {
// LOG.severe("Key not found: " + key);
keyValue = "???" + key + "???";
}
/* Message formating is expensive, try to avoid it */
if (param != null && param.length > 0) {
return MessageFormat.format(keyValue, param);
} else {
return keyValue;
}
}

How to parse a JSON Input stream

I am using java to call a url that returns a JSON object:
url = new URL("my URl");
urlInputStream = url.openConnection().getInputStream();
How can I convert the response into string form and parse it?
I would suggest you have to use a Reader to convert your InputStream in.
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
new JSONObject(responseStrBuilder.toString());
I tried in.toString() but it returns:
getClass().getName() + '#' + Integer.toHexString(hashCode())
(like documentation says it derives to toString from Object)
All the current answers assume that it is okay to pull the entire JSON into memory where the advantage of an InputStream is that you can read the input little by little. If you would like to avoid reading the entire Json file at once then I would suggest using the Jackson library (which is my personal favorite but I'm sure others like Gson have similar functions).
With Jackson you can use a JsonParser to read one section at a time. Below is an example of code I wrote that wraps the reading of an Array of JsonObjects in an Iterator. If you just want to see an example of Jackson, look at the initJsonParser, initFirstElement, and initNextObject methods.
public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable {
private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class);
private final InputStream inputStream;
private JsonParser jsonParser;
private boolean isInitialized;
private Map<String, Object> nextObject;
public JsonObjectIterator(final InputStream inputStream) {
this.inputStream = inputStream;
this.isInitialized = false;
this.nextObject = null;
}
private void init() {
this.initJsonParser();
this.initFirstElement();
this.isInitialized = true;
}
private void initJsonParser() {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonFactory jsonFactory = objectMapper.getFactory();
try {
this.jsonParser = jsonFactory.createParser(inputStream);
} catch (final IOException e) {
LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e);
throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e);
}
}
private void initFirstElement() {
try {
// Check that the first element is the start of an array
final JsonToken arrayStartToken = this.jsonParser.nextToken();
if (arrayStartToken != JsonToken.START_ARRAY) {
throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken);
}
// Initialize the first object
this.initNextObject();
} catch (final Exception e) {
LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
}
}
private void initNextObject() {
try {
final JsonToken nextToken = this.jsonParser.nextToken();
// Check for the end of the array which will mean we're done
if (nextToken == JsonToken.END_ARRAY) {
this.nextObject = null;
return;
}
// Make sure the next token is the start of an object
if (nextToken != JsonToken.START_OBJECT) {
throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken);
}
// Get the next product and make sure it's not null
this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { });
if (this.nextObject == null) {
throw new IllegalStateException("The next parsed object of the Json structure was null");
}
} catch (final Exception e) {
LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e);
throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e);
}
}
#Override
public boolean hasNext() {
if (!this.isInitialized) {
this.init();
}
return this.nextObject != null;
}
#Override
public Map<String, Object> next() {
// This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state
// Makes sure we're initialized first
if (!this.isInitialized) {
this.init();
}
// Store the current next object for return
final Map<String, Object> currentNextObject = this.nextObject;
// Initialize the next object
this.initNextObject();
return currentNextObject;
}
#Override
public void close() throws IOException {
IOUtils.closeQuietly(this.jsonParser);
IOUtils.closeQuietly(this.inputStream);
}
}
If you don't care about memory usage, then it would certainly be easier to read the entire file and parse it as one big Json as mentioned in other answers.
For those that pointed out the fact that you can't use the toString method of InputStream like this see https://stackoverflow.com/a/5445161/1304830 :
My correct answer would be then :
import org.json.JSONObject;
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
...
JSONObject json = new JSONObject(convertStreamToString(url.openStream());
If you like to use Jackson Databind (which Spring uses by default for its HttpMessageConverters), then you may use the ObjectMapper.readTree(InputStream) API. For example,
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(myInputStream);
use jackson to convert json input stream to the map or object http://jackson.codehaus.org/
there are also some other usefull libraries for json, you can google: json java
Use a library.
GSON
Jackson
or one of many other JSON libraries that are out there.
Kotlin version with Gson
to read the response JSON:
val response = BufferedReader(
InputStreamReader(conn.inputStream, "UTF-8")
).use { it.readText() }
to parse response we can use Gson:
val model = Gson().fromJson(response, YourModelClass::class.java)
This example reads all objects from a stream of objects,
it is assumed that you need CustomObjects instead of a Map:
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.getFactory().createParser( source );
if(parser.nextToken() != JsonToken.START_ARRAY) {
throw new IllegalStateException("Expected an array");
}
while(parser.nextToken() == JsonToken.START_OBJECT) {
// read everything from this START_OBJECT to the matching END_OBJECT
// and return it as a tree model ObjectNode
ObjectNode node = mapper.readTree(parser);
CustomObject custom = mapper.convertValue( node, CustomObject.class );
// do whatever you need to do with this object
System.out.println( "" + custom );
}
parser.close();
This answer was composed by using : Use Jackson To Stream Parse an Array of Json Objects and Convert JsonNode into Object
I suggest use javax.json.Json factory as less verbose possible solution:
JsonObject json = Json.createReader(yourInputStream).readObject();
Enjoy!
if you have JSON file you can set it on assets folder then call it using this code
InputStream in = mResources.getAssets().open("fragrances.json");
// where mResources object from Resources class
{
InputStream is = HTTPClient.get(url);
InputStreamReader reader = new InputStreamReader(is);
JSONTokener tokenizer = new JSONTokener(reader);
JSONObject jsonObject = new JSONObject(tokenizer);
}

Categories