Convert {key=value, key=value} to {"key":"value", "key":"value"} - java

I have a string that is being returned by an API which looks like this :
String result1 = "{username=null, tokenCode=00000000-0000-0000-0000-0000754d6034}";
I converted this to
String result2 = "{"username":"null", "tokenCode":"00000000-0000-0000-0000-0000754d6034"}";
Below is the code I am using it to convert to result2 from result1.
String result2 = new GsonBuilder().serializeNulls().create().toJson(result1);
Again I am doing this to make it a JSON object from String.
JSONObject jsonObject = new JSONObject(result2);
Is there a better way I can directly convert the "result1" to JSONObject without having to convert it to "result2".

Related

How to convert string to json string and object in java

This is My String
{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}
i want to convert it to json string
{"Line":"1","Direction":"incoming","LocalUsername":"xxx","AuthUsername":"31223","PeerUsername":"04232000113","Name":"04232000113","Server":"23424","Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote"}
Since it isn't nested, simply add " around : and ,, and after { and before }:
s = s.replaceAll("(?<=[{:,])|(?=[:,}])", "\"");
See demo on regex101.com.
Try using Gson library
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert a Java object to JSON by using toJson() method as shown below
String str = g.toJson(p);
If you don't have a POJO representing the data, it can be done generally using JsonElement.
Demo
String input = "{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}";
Gson g = new Gson();
JsonElement root = g.fromJson(input, JsonElement.class);
String result = g.toJson(root);
System.out.println(result);
Output
{"Line":1,"Direction":"incoming","LocalUsername":"xxx","AuthUsername":31223,"PeerUsername":"04232000113","Name":"04232000113","Server":23424,"Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote","Reason":"cancelNormalcallclearing"}

How to convert int to json in java

How can I convert an int to a JSON in java.
A simple Example:
int number = 5;
Gson gson = new Gson();
String numbersJson = gson.toJson(number);
return number;
but this is not working :( because i got 5 as returned value.
I want the json format: {"number": 5} as value
If you want a key-value, then either wrap to an Object or a Map:
Map<String, Integer> number = new HashMap<>();
number.put("number", 5);
String numbersJson = gson.toJson(number);
Just number 5 in json will be 5. What you need is an object with property number that has value of 5
JsonObject json = new JsonObject();
json.addProperty("number", 5);
String jsonAsString = json.toString(); // If you want it as string
System.out.println(jsonAsString); // prints {"number":5}

Converting json string to JSONArray in java?

I have this json string returned from a 3rd party api
{"msg":"xff","uuid":"44037b67-3629-4325-83e5-7a00cb78dfdf"}
When I try to parse it by the below code
JSONArray json = new JSONArray(message.toString());
JSONArray arr = json.getJSONArray(0);
String mess = arr.getJSONObject(0).getString("msg");
String uuid = arr.getJSONObject(0).getString("uuid");
System.out.println("message : "+mess);
System.out.println("uuid : "+uuid);
I get this below exception
org.json.JSONException: Value {"msg":"xff","uuid":"44037b67-3629-4325-83e5-7a00cb78dfdf"} of type org.json.JSONObject cannot be converted to JSONArray
What other way can I parse it?
You can use JSONObject instead:
JSONObject obj = new JSONObject(message);
String mess = obj.getString("msg");
String uuid = obj.getString("uuid");
System.out.println("message : "+mess);
System.out.println("uuid : "+uuid);

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

Parse JSON object with string and value only

I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;

Categories

Resources