For such a trivial example, it's pretty easy to produce a poorly-formed JSON String of your content and let JSONObject patch it up.
In a single expression:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|
1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}
If you really want to keep the 0.0 as Strings:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|
1:\"$2\",")))
// {"art":"0.0","comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}
If you want to account for possible extraneous whitespaces:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|
1:$2,")))
.. will work with inputs like "art, 0.0, comedy, 0.0, action, 0.0, crime, 0.0, animals, 0.0" and other cases.
Disclaimer: it's not crazy-sexy code but drop in a one-line comment and it could be reasonable so long as the data structure stays simplistic.
Answer from ccjmne on Stack OverflowFor such a trivial example, it's pretty easy to produce a poorly-formed JSON String of your content and let JSONObject patch it up.
In a single expression:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|
1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}
If you really want to keep the 0.0 as Strings:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|
1:\"$2\",")))
// {"art":"0.0","comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}
If you want to account for possible extraneous whitespaces:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|
1:$2,")))
.. will work with inputs like "art, 0.0, comedy, 0.0, action, 0.0, crime, 0.0, animals, 0.0" and other cases.
Disclaimer: it's not crazy-sexy code but drop in a one-line comment and it could be reasonable so long as the data structure stays simplistic.
You should use Map instead of Array (List of key/value pair is Map, not Array).
1 way: Using JsonObject
String [] arrayStr=strVal.split(",");
JsonObjectBuilder builder = Json.createObjectBuilder()
String key = null;
for (String s: arrayStr){
if(key == null) {
key = s;
} else {
builder.add(key, s);
key = null;
}
}
JsonObject value = builder.build();
2 way: Using Map
String [] arrayStr=strVal.split(",");
Map<String,String> map = new HashMap<>();
String key = null;
for (String s: arrayStr){
if(key == null) {
key = s;
} else {
map.put(key, s);
key = null;
}
}
// convert Map to Json using any Json lib (Gson, Jackson and so on)
Wrap the string in "[]" and then use the JSON parser of your choice.
There is Java Lib called Quick-json - A java library to convert json string to java objects & java objects to json string. parse/generate json the way you want quickly. configure/validate json at every level.
Please refer for Quick- Json Lib https://code.google.com/p/quick-json/ has good example's as well as explanation.
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);
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);
Just remove the internal loop
String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 = stringFromProc.split(";"); // simply use ;
// array1[0] = SONY,20,30,40
// array1[1] = LG,1,4,8
JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split(","); // simply use ,
// create jsonobjects
// when i=0 mean for sony and next time i = 1 mean for LG
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
// put every object in array
jsonArrayRET.add(jsonSubObject);
}
// finally put array in reported jsonobject
jsonFinal.put("reported", jsonArrayRET);
Note : ; and , are not special regular expressions characters so no escaping \\ is required and instead of long info just read about character class []
Move
jsonFinal.put("reported", jsonArrayRET);
outside of 2nd loop, you are overwritting reported object.
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split("[\\,]");
for(int j=0;j<array2.length;j++){
System.out.println(array2[j]);
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
jsonArrayRET.add(jsonSubObject);
}
jsonFinal.put("reported", jsonArrayRET);
}
This will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
In JSON, numbers don't need double quotes, so you could just append [ and ] to either end of the string, resulting in the string "[1,4,5,11,58,96]" and you will have a JSON Array of numbers.