开发者

how to convert object to string in java

开发者 https://www.devze.com 2023-03-06 19:07 出处:网络
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

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();
        Strin开发者_如何学运维g[] 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消