How to convert any Object to String? - java

Here is my code:
for (String toEmail : toEmailList)
{
Log.i("GMail","toEmail: "+toEmail);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
}
Please give me some suggestion about this.

To convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3

If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3
pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12</version>
</dependency>
code:
ToStringBuilder.reflectionToString(yourObject)

"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.
Declaration: java.lang.Object.toString()
Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.
Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );
You can find the complete code here.
You can test the code here.

I've written a few methods for convert by Gson library and java 1.8 .
thay are daynamic model for convert.
string to object
object to string
List to string
string to List
HashMap to String
String to JsonObj
//saeedmpt
public static String convertMapToString(Map<String, String> data) {
//convert Map to String
return new GsonBuilder().setPrettyPrinting().create().toJson(data);
}
public static <T> List<T> convertStringToList(String strListObj) {
//convert string json to object List
return new Gson().fromJson(strListObj, new TypeToken<List<Object>>() {
}.getType());
}
public static <T> T convertStringToObj(String strObj, Class<T> classOfT) {
//convert string json to object
return new Gson().fromJson(strObj, (Type) classOfT);
}
public static JsonObject convertStringToJsonObj(String strObj) {
//convert string json to object
return new Gson().fromJson(strObj, JsonObject.class);
}
public static <T> String convertListObjToString(List<T> listObj) {
//convert object list to string json for
return new Gson().toJson(listObj, new TypeToken<List<T>>() {
}.getType());
}
public static String convertObjToString(Object clsObj) {
//convert object to string json
String jsonSender = new Gson().toJson(clsObj, new TypeToken<Object>() {
}.getType());
return jsonSender;
}

I am try to convert Object type variable into string using this line of code
try this to convert object value to string:
Java Code
Object dataobject=value;
//convert object into String
String convert= String.valueOf(dataobject);

I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString() function on a String Object.

try this one
ObjectMapper mapper = new ObjectMapper();
String oldSerial = mapper.writeValueAsString(list);

Related

Replace json to java string [duplicate]

This question already has an answer here:
json object convert to string java
(1 answer)
Closed 2 years ago.
Hi Guys I'm new to programming.
In my java code i have string like this.
String json ="{"name":"yashav"}";
Please help me out to print the values using pre-build java functions.
Expected output should be like below
name=yashav
First of all its not JSON.
If you want to work for actual JSON. There are many libraries which help you to transfer string to object.
GSON is one of those libraries. Use this to covert object then you can use keys to get values. Or you can iterate whole HashMap as per your requirements.
https://github.com/google/gson
{name:yashav} this is not a valid JSON format.
If you have {"name": "yashav"} you can use Jackson to parse JSON to java object.
class Person {
String name;
...
}
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue("{\"name\" : \"mkyong\"}", Person.class);
Forst of all, given String is NOT a json. It should be "{\"name\":\"yashav\"}". If you have a correct json string, you can use JacksonUtils.
Define a model:
class Url {
private String name;
public String getName() {
return name;
}
}
And parse the json string:
String json = "{\"name\":\"yashav\"}";
Url url = JsonUtils.readValue(json, Url.class);
System.out.format("name = %s", url.getName());
Another way is to use Regular Expression:
public static void main(String... args) {
String url = "{name:yashav}";
Pattern pattern = Pattern.compile("\\{(?<key>[^:]+):(?<value>[^\\}]+)\\}");
Matcher matcher = pattern.matcher(url);
if (matcher.matches())
System.out.format("%s = %s\n", matcher.group("key"), matcher.group("value"));
}
And finally, you can use plain old String operations:
public static void main(String... args) {
String url = "{name:yashav}";
int colon = url.indexOf(':');
String key = url.substring(1, colon);
String value = url.substring(colon + 1, url.length() - 1);
System.out.format("%s = %s\n", key, value);
}

How to Convert a Multiple Array to Json Array and add Jsons to a hashmap

I want to convert this Json String to an Array.
My hashmap named "HASHMRM"
this is my Json String:
[
{"id":1,"name":"hamid"},
{"id":2,"name":"mohamad"},
{"id":3,"name":"ali"},
{"id":4,"name":"john"},
{"id":5,"name":"smith"}
]
and I wanna to convert this Json String To an Array like this
String myJsonstring ="[{"id":1,"name":"hamid"},{"id":2,"name":"mohamad"},{"id":3,"name":"ali"},{"id":4,"name":"john"},{"id":5,"name":"smith"}]";
string[] AA = Jsons.....
int i =0;
while(i<string.lenght)
{
HASHMRM.put(AA[i].split()//First, AA[i].split()//second);
i++;
}
Use Gson.
First, you need POJO class that matches your data.
class MyUser {
int id;
String name;
}
Then, convert your string to List of POJO class.
// This is your string.
String myJsonString = "[{\"id\":1,\"name\":\"hamid\"},{\"id\":2,\"name\":\"mohamad\"},{\"id\":3,\"name\":\"ali\"},{\"id\":4,\"name\":\"john\"},{\"id\":5,\"name\":\"smith\"}]";
// Create new Gson object.
Gson gson = new Gson();
// Convert
List<MyUser> userList = gson.fromJson(myJsonString, new TypeToken<List<MyUser>>() {
}.getType());
Next, use it!
for (MyUser u : userList) {
HASHMRM.put(u.id, u.name);
}
Remember: Instead of using the HASHMRM as variable name, I suggest you to use java conventional camel case name HashMRM.

Android: How to add existing JSONObject to existing key

I have a data structure like this:
source: {
property_1: String,
property_2: String,
property_3: {
property_31: String
}
}
I want to have a function like this:
private JSONObject mergeProperty(JSONObject source, String propertyName, JSONObject newData)
in which, source is data above, propertyName = "property_3", and
newData: {
property_32: String,
property_33: int
}
with result of calling mergeProperty(source, "property_3", newData) as:
output: {
property_1: String,
property_2: String,
property_3: {
property_31: String,
property_32: String,
property_33: int
}
}
Is there any simple method to achieve this without having to map the JSON object to HashMap first? I found no built-in JSONObject function which corelates to my problem.
If I got your intention right, this code must do the job. Please, note, that this will mutate original source, so you might need to pass a copy, if mutating original one is not what you want. Also, here I assume that propertyName is on the first level of your source JSON, and is JSON, too, else this will throw a JSONException.
JSONObject mergeTarget = source.getJSONObject(propertyName);
Iterator<String> keys = newData.keys();
while (keys.hasNext()) {
String key = keys.next();
mergeTarget.put(key, newData.get(key));
}
Try accumulate method of org.json.JSONObject.
Below code may be useful to you.
public class Test {
public static void main(String[] args){
System.out.println("test");
JSONObject source = new JSONObject("{\"property_1\":\"String\",\"property_2\":\"String\",\"property_3\":{\"property_31\":\"String\"}}");
JSONObject newData = new JSONObject("{\"property_32\":\"String\",\"property_33\":\"int\"}");
System.out.println("Before merge :"+source.toString());
mergeProperty(source, "property_3", newData);
System.out.println("After merge :"+source.toString());
}
private static void mergeProperty(JSONObject source, String property, JSONObject newData){
for (Object key : newData.keySet()){
String keyStr = (String)key;
Object keyvalue = newData.get(keyStr);
source.getJSONObject(property).accumulate(keyStr , keyvalue);
}
}
}

Convertig Json to List

I am trying to read and write a Json object to my database and I'm not getting how to convert the string you get from the database to a string and how I can use it later tp write back the changed list into my database again.
So when I'm asking the database for the field I want, I get this string back:
["[\"pw1\",\"pw2\",\"pw3\"]"]
Then I go and create an object of my class LastPasswords
List<String> passwordList = (List<String>) controllerServlet.getMacroDatabaseManager().executeNativeQuery(queryGet);
LastPasswords lastPasswords = new LastPasswords(passwordList);
Gson gson = new Gson();
String Json = gson.toJson(lastPasswords);
Here is the LastPasswords class
public class LastPasswords {
private List<String> passwords;
public LastPasswords(List<String> passwords) {
this.passwords = passwords;
}
public List<String> getPasswords(){
return passwords;
}
public void setPasswords(List<String> passwords){
this.passwords = passwords;
}
}
Then when I have this json string I try to get it as a list but I don't get the list.
lastPasswords.setPasswords((List<String>) gson.fromJson(banana, LastPasswords.class));
passwordList = lastPasswords.getPasswords();
Thanks for helping.
You can use com.google.gson.reflect.TypeToken.TypeToken to define return type of fromJson method.
Then, àter you have the list, you can create a new LastPasswords to use.
String json = "[\"pw1\",\"pw2\",\"pw3\"]";
Gson gson = new Gson();
List<String> list = gson.fromJson(json, new TypeToken<List<String>>() {}.getType());
System.out.println(list.size());
System.out.println(list);
Output:
3
[pw1, pw2, pw3]
You may use TypeToken to load the json string into a custom object.
String json = "[\"pw1\",\"pw2\",\"pw3\"]";
List<String> list = gson.fromJson(json, new TypeToken<List<String>>(){}.getType());
Or for an list of list of String
String json = "[\"[\"pw1\",\"pw2\",\"pw3\"]\"]";
List<List<String>> list = gson.fromJson(json, new TypeToken<List<List<String>>>(){}.getType());
list.get(0).get(0) == "pw1"
I would like to recommend to keep a Password class instead of keeping a ListPassword class.
Let us assume, you've a Password class like this.
public class Password {
public String password;
// Getter and setter
}
Now when you read the json string using gson, you might have to do this.
Password[] passwordArray = gson.fromJson(json, Password[].class);
This will map the json string into an array of Password. Then you might consider populating them in a list if you like.
List<Password> passwordList = Arrays.asList(passwordArray);

How to provide JSON input directly as a String argument

The following code prints the following as input, but I would like to pass this JSON string as input directly to parse method (preferably as string argument). How should I do that?
{"val1":"v1","val2":"v2"}
import com.google.gson.*;
public class ParseJSON {
String val1;
String val2;
transient String val3;
public static void main(String[] args) {
Gson gson = new GsonBuilder().create();
ParseJSON parseJson = new ParseJSON();
parseJson.val1 = "v1";
parseJson.val2 = "v2";
parseJson.val3 = "v3";
String requestBody = gson.toJson(parseJson);
System.out.println(requestBody);
JsonParser parser = new JsonParser();
// JsonArray array = parser.parse(requestBody).getAsJsonArray();
}
}
The JSON that is being created would be considered a JSON object, not an array. To parse it correctly, you would need to call:
JsonObject object = parser.parse(requestBody).getAsJsonObject();
A JSON array would look more like this:
[{"va1": "v1", "val2": "v2", "val3": "v3"}, {"val4": "v4", "val4": "v5", "val5": "v6"}]
That's a JSON array containing two JSON objects. JSON arrays have similar style to arrays you see in Java, they have [ ] brackets and contain a comma separated list of objects/arrays/primitives.
Additionally, you can parse it like this as well:
JsonElement element = parser.parse(requestBody);
Once you have a JsonElement you can call methods like isJsonArray() or isJsonObject() to find out what the top level JSON element is for the String you've parsed.
*You should do that in a following code for your request*
static String val1 = "v1";
static String val2 = "v2";
transient String val3;
public static void main(String[] args) {
JSONArray arrayTable = new JSONArray();
JSONObject node = new JSONObject();
node.put("val1", val1);
node.put("val2", val2);
arrayTable.add(node);
System.out.println(arrayTable);
}
**Dependency lib**:
<dependency>
<groupId>json</groupId>
<artifactId>json</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>

Categories

Resources