将逗号分隔的字符串转换为Json字符串

时间:2019-07-09 06:34:39

标签: java json string

String input = "Vish,Path,123456789";

预期输出为Json字符串,并且线程安全= {“名称”:“ Vish”,“姓氏”:“路径”,“移动”:“ 123456789”}

我尝试使用

 GsonBuilder gsonBuilder = new GsonBuilder(); 
 Gson gson = gsonBuilder.create(); 

但是每次我创建新对象-

MappingObject[] studentArray = new MappingObject[1]; 
studentArray[0] = new MappingObject("Vish","Path","123456789"); 

我使用split()分隔了此逗号分隔的字符串

 System.out.println("JSON "+gson.toJson(studentArray));

2 个答案:

答案 0 :(得分:1)

如果您不想使用任何库,则必须用逗号分割字符串并创建一个新的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());

输出:

  

{“ name”:“ Vish”,“ surname”:“ Path”,“ mobile”:“ 123456789”}

如果您想使用库,则可以在Jackson之前实现。简单地创建一个类,并由此创建json。

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);

答案 1 :(得分:1)

您将必须创建一个地图:

Map<String,String> jsonMap = new HashMap<String,String>();
jsonMap.put("name","Vish");
jsonMap.put("surname","Path");
jsonMap.put("mobile","123456789");

然后使用com.google.gson JSONObject:     JSONObject jsonObj =新的JSONObject(jsonMap);