Convert comma separated String into Json string - java

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

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

Related

Using Gson to convert a string object to JSON string in Java

Let's say we have the following string:
String x = "abc";
My question is how would I use the Gson library to convert the given string, to the following JSON string:
{
x : "abc"
}
Of course I could have created a new class that wraps the string object, and convert it to a JSON string, but it didn't seem necessary. Anyway, the solution I found was this:
JsonObject x = new JsonObject();
x.addProperty("x", "abc");
String json = x.toString();
http://www.studytrails.com/java/json/java-google-json-parse-json-to-java.jsp
class Albums {
public String x;
}
Lets convert this to JSON and see how it looks
import com.google.gson.Gson;
public class JavaToJsonAndBack {
public static void main(String[] args) {
Albums albums = new Albums();
albums.x= "abc";
Gson gson = new Gson();
System.out.println(gson.toJson(albums));
}
}
This is how the resulting JSON looks like
{"x":"abc"}

Json Object Array Write in Java line by line

I have a Array with some value
when i store that array i got result like this
[{"id":56678,"Name":"Rehman Agarwal"},{"id":66849,"Name":"Rasul Guha"}]
means in a single line.
but I just want to get output like
[{"id":56678,"Name":"Rehman Agarwal"},
{"id":66849,"Name":"Rasul Guha"}]
new line after JSON object ..
How to do it ?
EDIT : i use JSONObject && JSONArray for create json Object and array respectively
Using gson library you can pretty print your json strings like below -
public static String toPrettyFormat(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
return prettyJson;
}
And call it like below -
public void testPrettyPrint() {
String compactJson = "{\"playerID\":1234,\"name\":\"Test\",\"itemList\":[{\"itemID\":1,\"name\":\"Axe\",\"atk\":12,\"def\":0},{\"itemID\":2,\"name\":\"Sword\",\"atk\":5,\"def\":5},{\"itemID\":3,\"name\":\"Shield\",\"atk\":0,\"def\":10}]}";
String prettyJson = toPrettyFormat(compactJson);
System.out.println("Compact:\n" + compactJson);
System.out.println("Pretty:\n" + prettyJson);
}

How to Convert String Array JSON in a Java Object [duplicate]

This question already has answers here:
Convert a JSON string to object in Java ME?
(14 answers)
Closed 8 years ago.
i need to convert this String JSON to a Java Object:
{"estabelecimento":[{"id":"5","idUsuario":"5","razaoSocial":"Bibi LTDA","nomeFantasia":"BibiPizza","telefone":"22121212","email":"ronaldo#bibi.com","gostaram":"0"},{"id":"8","idUsuario":"1","razaoSocial":"Nestor Latuf LTDA","nomeFantasia":"Nestor Sorvetes","telefone":"32343233","email":"nestor#Sorvete.com","foto":"","gostaram":"0"},{"id":"9","idUsuario":"1","razaoSocial":"Comercio Alimenticio Rivaldo","nomeFantasia":"Rogers Burguer","telefone":"210021020","email":"roger#gmail.com","foto":"","gostaram":"0"}]}
I try this, but not work:
//JSONArray jArr = new JSONArray(br.toString());
//JSONObject jObj = new JSONObject(br.toString());
//JSONArray jArr = jObj.getJSONArray("list");
JSONArray jArr = new JSONArray(br.toString());
for (int i=0; i < jArr.length(); i++) {
JSONObject obj = jArr.getJSONObject(i);
estabelecimento.setId(obj.getLong("id"));
estabelecimento.setIdUsuario(obj.getLong("idUsuario"));
estabelecimento.setRazaoSocial(obj.getString("razaoSocial"));
estabelecimento.setNomeFantasia(obj.getString("nomeFantasia"));
estabelecimento.setTelefone(obj.getString("telefone"));
estabelecimento.setEmail(obj.getString("email"));
estabelecimento.setGostaram(obj.getInt("gostaram"));
estabelecimentoList.add(estabelecimento);
}
con.disconnect();
How can i obtain a Java Object? Someone can help? tks.
You can use the Gson lib of google:
public class MyClass {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods needed
}
String str = {"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]};
com.google.gson.Gson gson = new com.google.gson.Gson();
//To convert json string to class use fromJson
MyClass obj = gson.fromJson(str, MyClass .class);
//To convert class object to json string use toJson
String json = gson.toJson(obj);
At high level two major steps:
Generate a Java class from your JSON, e.g. by using this generator or similar: http://www.jsonschema2pojo.org/
Use Jackson processor to deserialize your JSON file:
ObjectMapper mapper = new ObjectMapper();
YourGeneratedClass obj = (YourGeneratedClass) mapper.readValue(new File("path-to-your-json-file"), YourGeneratedClass.class);
More about Jackson: http://jackson.codehaus.org/
You can also create YourGeneratedClass manually if you feel comfortable enough with this.

How to parse JSON Array (Not Json Object) in Android

I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);

How to convert a String to JsonObject using gson library

Please advice how to convert a String to JsonObject using gson library.
What I unsuccesfully do:
String string = "abcde";
Gson gson = new Gson();
JsonObject json = new JsonObject();
json = gson.toJson(string); // Can't convert String to JsonObject
You can convert it to a JavaBean if you want using:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.fromJson(jsonString, JavaBean.class)
To use JsonObject, which is more flexible, use the following:
String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());
Which is equivalent to the following:
JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
I do this, and it worked.
You don't need to use JsonObject. You should be using Gson to convert to/from JSON strings and your own Java objects.
See the Gson User Guide:
(Serialization)
Gson gson = new Gson();
gson.toJson(1); // prints 1
gson.toJson("abcd"); // prints "abcd"
gson.toJson(new Long(10)); // prints 10
int[] values = { 1 };
gson.toJson(values); // prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class)
String emailData = {"to": "abc#abctest.com","subject":"User details","body": "The user has completed his training"
}
// Java model class
public class EmailData {
public String to;
public String subject;
public String body;
}
//Final Data
Gson gson = new Gson();
EmailData emaildata = gson.fromJson(emailData, EmailData.class);
Looks like the above answer did not answer the question completely.
I think you are looking for something like below:
class TransactionResponse {
String Success, Message;
List<Response> Response;
}
TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);
where my response is something like this:
{"Success":false,"Message":"Invalid access token.","Response":null}
As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.
Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
Note that as of Gson 2.8.6, instance method JsonParser.parse has been deprecated and replaced by static method JsonParser.parseString:
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
if you just want to convert string to json then use:
use org.json: https://mvnrepository.com/artifact/org.json/json/20210307
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
import these
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
Now convert it as
//now you can convert string to array and object without having complicated maps and objects
try {
JSONArray jsonArray = new JSONArray("[1,2,3,4,5]");
//you can give entire jsonObject here
JSONObject jsonObject= new JSONObject("{\"name\":\"test\"}") ;
System.out.println("outputarray: "+ jsonArray.toString(2));
System.out.println("outputObject: "+ jsonObject.toString(2));
}catch (JSONException err){
System.out.println("Error: "+ err.toString());
}
You can use the already Gson existing method :
inline fun <I, reified O> I.convert():O {
val json = gson.toJson(this)
return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

Categories