Reputation: 146
String input = "Vish,Path,123456789";
Expected output as Json string, and thread safe = {"name":"Vish","surname":"Path","mobile":"123456789"}
I tried by using
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
But every time I'm creating new Object -
MappingObject[] studentArray = new MappingObject[1];
studentArray[0] = new MappingObject("Vish","Path","123456789");
I separated this comma separated string by using split()
System.out.println("JSON "+gson.toJson(studentArray));
Upvotes: 4
Views: 2010
Reputation: 3232
If you don't want to use any library then you have to split string by comma and make a new String
.
String input = "Vish,Path,123456789";
String[] values=input.split("[,]");
StringBuffer json = new StringBuffer();// StringBuffer is Thread Safe
json.append("{")
.append("\"name\": \"").append(values[0]).append("\",")
.append("\"surname\": \"").append(values[1]).append("\",")
.append("\"mobile\": \"").append(values[2]).append("\"")
.append("}");
System.out.println(json.toString());
Output :
{"name": "Vish","surname": "Path","mobile": "123456789"}
If you want to use library then you will achive this by Jackson
. Simple make a class and make json by it.
public class Person {
private String name;
private String surname;
private String mobile;
// ... getters and Setters
}
String input = "Vish,Path,123456789";
String[] values=input.split("[,]");
Person person = new Person(values[0],values[1],values[2]);// Assume you have All Argumets Constructor in specified order
ObjectMapper mapper = new ObjectMapper(); //com.fasterxml.jackson.databind.ObjectMapper;
String json = mapper.writeValueAsString(person);
Upvotes: 1
Reputation: 390
You will have to create a Map:
Map<String,String> jsonMap = new HashMap<String,String>();
jsonMap.put("name","Vish");
jsonMap.put("surname","Path");
jsonMap.put("mobile","123456789");
Then use com.google.gson JSONObject: JSONObject jsonObj = new JSONObject(jsonMap);
Upvotes: 1