Stringbuffer to json java

Stringbuffer to json java

JSON Parser and Generator. This class provides some static methods to convert POJOs to and from JSON notation. The mapping from JSON to java is:

object --> Map array --> Object[] number --> Double or Long string --> String null --> null bool --> Boolean
String --> string Number --> number Map --> object List --> array Array --> array null --> null Boolean--> boolean Object --> string (dubious!)

The interface JSON.Convertible may be implemented by classes that wish to externalize and initialize specific fields to and from JSON objects. Only directed acyclic graphs of objects are supported. The interface JSON.Generator may be implemented by classes that know how to render themselves as JSON and the toString(Object) method will use JSON.Generator.addJSON(Appendable) to generate the JSON. The class JSON.Literal may be used to hold pre-generated JSON object. The interface JSON.Convertor may be implemented to provide static converters for objects that may be registered with registerConvertor(Class, Convertor) . These converters are looked up by class, interface and super class by getConvertor(Class) . If a JSON object has a «class» field, then a java class for that name is loaded and the method convertTo(Class, Map) is used to find a JSON.Convertor for that class. If a JSON object has a «x-class» field then a direct lookup for a JSON.Convertor for that class name is done (without loading the class).

Nested Class Summary

A Literal JSON generator A utility instance of JSON.Generator that holds a pre-generated string on JSON text.

Источник

Java Programs and Examples with Output

How to Convert Java Objects to JSON String and vice versa by using GSON library

GSON is the library that can be used to convert Java objects in to their JSON representation.It can also be used to convert a JSON string to an equivalent Java object.

Gson can work with arbitrary Java objects including pre-existing objects that you do not have source- code of.

Provide easy to use mechanisms like toString() and constructor (factory method) to convert Java to JSON and vice-versa.

import java.util.ArrayList; public class DataObject < private ArrayListempList = new ArrayList(); public ArrayList getEmpList() < return empList; >public void setEmpList(ArrayList empList) < this.empList = empList; >public String toString() < StringBuffer employeeList = new StringBuffer(); String newLine = System.getProperty("line.separator"); employeeList.append("Employee List ::"); employeeList.append(newLine); for(Employee emp : empList )< employeeList.append(emp.toString()); employeeList.append(newLine); >return employeeList.toString(); > >
public class Employee < private String empId; private String empName; private String empAge; private String empSal; public String getEmpId() < return empId; >public void setEmpId(String empId) < this.empId = empId; >public String getEmpName() < return empName; >public void setEmpName(String empName) < this.empName = empName; >public String getEmpAge() < return empAge; >public void setEmpAge(String empAge) < this.empAge = empAge; >public String getEmpSal() < return empSal; >public void setEmpSal(String empSal) < this.empSal = empSal; >public String toString() < StringBuffer empDetails = new StringBuffer(); String newLine = System.getProperty("line.separator"); empDetails.append("Employee Details ::"); empDetails.append(newLine); empDetails.append("Emp Id : " + empId); empDetails.append(newLine); empDetails.append("Emp Age : " + empAge); empDetails.append(newLine); empDetails.append("Emp Name : " + empName); empDetails.append(newLine); empDetails.append("Emp Sal : " + empSal); empDetails.append(newLine); return empDetails.toString(); >>
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import com.google.gson.Gson; /** * * * GSONExample is a Java Class which will give the example to convert * 1. Java Object to Json Object * 2. Json Object to Java Object * * Gson - Gson is a Java library that can be used to convert Java Objects into their JSON representation. * It can also be used to convert a JSON string to an equivalent Java object */ public class GSONExample < public static void main(String[] args) < Gson gson = new Gson(); // Form the Data object DataObject employees = formJavaObject(); // Convert Object to json String String json = gson.toJson(employees); System.out.println(json); //Convert Json String to Java object DataObject obj = gson.fromJson(json, DataObject.class); System.out.println(obj.toString()); // To store the Json Value to File called emp.json setJsonValueToFile(); //To get the Json String from emp.Json file and convert into JavaObject getJsonValueFromFile(); >/** * formJavaObject - To form the Employee data Object * @return DataObject */ private static DataObject formJavaObject() < DataObject dataObject = new DataObject(); ArrayListempList = new ArrayList(); Employee emp1 = new Employee(); emp1.setEmpId("379023"); emp1.setEmpAge("23"); emp1.setEmpName("Kanchu"); emp1.setEmpSal("10000"); Employee emp2 = new Employee(); emp2.setEmpId("111111"); emp2.setEmpAge("23"); emp2.setEmpName("Lakshman"); emp2.setEmpSal("10000"); empList.add(emp1); empList.add(emp2); dataObject.setEmpList(empList); System.out.println(dataObject.toString()); return dataObject; > /** * setJsonValueToFile - To store the Json String to emp.json file */ private static void setJsonValueToFile() < DataObject dataObject = formJavaObject(); Gson gson = new Gson(); String json = null; try < // Convert Object to Json String json = gson.toJson(dataObject); // Write json data to a file named "emp.json" FileWriter writer = new FileWriter("C:\\Laxman\\emp.json"); writer.write(json); writer.close(); >catch (IOException e) < e.printStackTrace(); >System.out.println(json); > /** * getJsonValueFromFile - To get the Json String from emp.json and convert to Employee data object */ private static void getJsonValueFromFile() < Gson gson = new Gson(); try < BufferedReader br = new BufferedReader(new FileReader("C:\\Laxman\\emp.json")); // Convert Json String to Java Object DataObject empListObj = gson.fromJson(br, DataObject.class); System.out.println(empListObj); >catch (IOException e) < e.printStackTrace(); >> > 

Employee List ::
Employee Details ::
Emp Id : 999999
Emp Age : 23
Emp Name : Raj
Emp Sal : 10000

Читайте также:  Css text color animation

Employee Details ::
Emp Id : 111111
Emp Age : 23
Emp Name : ABC
Emp Sal : 10000

Employee Details ::
Emp Id : 111111
Emp Age : 23
Emp Name : ABC
Emp Sal : 10000

Employee List ::
Employee Details ::
Emp Id : 999999
Emp Age : 23
Emp Name : Raj
Emp Sal : 10000

Employee Details ::
Emp Id : 111111
Emp Age : 23
Emp Name : ABC
Emp Sal : 10000

Employee Details ::
Emp Id : 111111
Emp Age : 23
Emp Name : ABC
Emp Sal : 10000

Источник

Javascript how convert stringbuffer to jsonarray in java

The primary benefit that using something like Gson provides is that you can now use all of Java’s type checking by default, instead of having to manage attribute names and types yourself. E.g. indexOf(«http:») and then copy to the last occcurence of «. Hope this helps Solution: Instead of using the function, you can convert your String to a and then iterate throw the array Solution 1: The parser class as requested: To make use of this JsonParser, for example in your code now: Solution 2: If your response is in fixed format, example: In Java, you can use the following code: Where you have the Car class as:

Convert String to JSONArray (not JsonArray from gson) [duplicate]

JSONObject jObject = new JSONObject(STRING_FROM_ABOVE); JSONArray jArray = jObject.getJSONArray("myArray"); 

The «string_from_above» is not a Json Array, it’s a Json object, containing one attribute (myArray) which is a Json Array 😉

While parsing, add values to objects and ArrayLists or however the way you want to use it. Good luck.

JSONObject jo = new JSONObject(STRING_FROM_ABOVE); JSONArray rootArray= jo.getJSONArray("myArray"); int rootArrayLength=rootArray.length(); for(int i=0;i // create object and make a list 

Just to throw another method into the mix here, I’d like to recommend taking a look at Gson. Gson is a library that makes serialization to and deserialization from Java objects a snap. For example, with your string, you could do this:

// Declare these somewhere that is on the classpath public class ArrayItem < public int id; public double att1; public boolean att2; >public class Container < public ListmyArray; > // In your code Gson gson = new Gson(); Container container = gson.fromJson(json, Container.class); for(ArrayItem item : container.myArray) < System.out.println(item.id); // 1, 2, 3 System.out.println(item.att1); // 14.2, 13.2, 13.0 System.out.println(item.att2); // false, false, false >

Similarly, you can go backwards very easily too.

String jsonString = gson.toJson(container); // jsonString no contains something like this: // <"myArray":[<"id":1,"att1":14.2,"att2":false>,,]> 

The primary benefit that using something like Gson provides is that you can now use all of Java’s type checking by default, instead of having to manage attribute names and types yourself. It also allows you to do some fancy stuff like replicating type hierarchies that make managing large numbers of json messages a snap. It works great with Android, and the jar itself is tiny and doesn’t require any additional dependencies.

Converting a Java ArrayList of strings to a JavaScript, I’d like to put this data in a JavaScript variable on a JSP page I’m working on. My first thought was to include it directly, e.g.: var myArray =

StringBuffer Replace on JSON

What library are you using for working with json? Perhaps this one:

If so you can do it like this:

JSONObject myobj = JSONObject(your_buffer); myobj.getString("thumbnailURL"); 

That is one way. Other method would be simply to use standard string functions. E.g. indexOf(«http:») and then copy to the last occcurence of «.

Java — Converting String of Json to JsonObject, I have a String of Json received from a web service http get request. I would like to turn the string that I have formed into a JsonObject. The question …

Split json object from json array in java

Instead of using the split function, you can convert your String to a JSONArray and then iterate throw the array

JSONArray jsonArray = new JSONArray(response.toString()); for(int i=0; i

How to convert jsonString to JSONObject in Java, Just do a very simple approach as below: JSONObject obj = new JSONObject (); obj.put («phonetype», «N95»); obj.put («cat», «WP»); Now obj is your …

How to convert specific JSONArray to JAVA object?

The parser class as requested:

public class JsonParser < public static Response toJavaObject(String str) < String[] fields = str.split(","); Response res = new Response(); res.setId(Integer.valueOf(fields[0].substring(1))); res.setType(fields[1].replaceAll("\"", "")); Details dtl = new Details(); dtl.setId(Long.valueOf(fields[2].substring(1))); dtl.setTimestamp(Long.valueOf(fields[3])); dtl.setAmount(Double.valueOf(fields[4])); dtl.setPrice(Double.valueOf(fields[5].substring(0, fields[5].length() - 2))); res.setDetails(dtl); return res; >> class Details < public Long id; public Long timestamp; public Double amount; public Double price; public Long getId() < return id; >public void setId(Long id) < this.id = id; >public Long getTimestamp() < return timestamp; >public void setTimestamp(Long timestamp) < this.timestamp = timestamp; >public Double getAmount() < return amount; >public void setAmount(Double amount) < this.amount = amount; >public Double getPrice() < return price; >public void setPrice(Double price) < this.price = price; >> class Response < public Integer id; public String type; public Details details; public Integer getId() < return id; >public void setId(Integer id) < this.id = id; >public String getType() < return type; >public void setType(String type) < this.type = type; >public Details getDetails() < return details; >public void setDetails(Details details) < this.details = details; >> 

To make use of this JsonParser,

for example in your code now:

public static void main(String args[]) < String str = "[68,\"te\",[80588348,1508768162000,0.01569882,5700.8]]"; Response res = JsonParser.toJavaObject(str); // your logic below. >

If your response is in fixed format,

In Java, you can use the following code:

Car car = objectMapper.readValue(jsonString, Car.class); 

Where you have the Car class as:

How to convert Java String to JSON Object, When a constructor calls for a java.lang.Object class, more than likely it’s really telling you that you’re expected to create your own class (since all …

Источник

How to create dynamic JSON by Java?

Jackson provide Java api’s to create JSON on runtime . These api’s can handle different type of data and objects.

Jacson API’s

Writing Root Object JsonGenerator.writeStartObject(); JsonGenerator.writeEndObject(); Writing Sub Object JsonGenerator.writeObjectFieldStart(); JsonGenerator.writeEndObject(); Writing Array JsonGenerator.writeArrayFieldStart() JsonGenerator.writeEndObject(); Writing Field Level JsonGenerator.writeNumberField(); JsonGenerator.writeStringField(); JsonGenerator.writeBooleanField();

Pre-Requisite

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

 com.fasterxml.jackson.core jackson-databind 2.8.5  

Example

In below example by Jacson API’s generating JSON on runtime and writing on file.

package test.facingissesonit.json.jacson; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; public class JsonStreamWriteToFile < public static void main(String[] args) < Student student = sampleStudentObject(); try < JsonGenerator jsonGenerator = new JsonFactory().createGenerator(new FileOutputStream("student_data.txt")); // for pretty formatted printing jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()); // start root from here jsonGenerator.writeStartObject(); jsonGenerator.writeNumberField("rollNumber", student.getRollNumber()); jsonGenerator.writeStringField("firstName", student.getFirstName()); jsonGenerator.writeStringField("lastName", student.getLastName()); jsonGenerator.writeBooleanField("permanent", student.isPermanent()); jsonGenerator.writeObjectFieldStart("address"); // object writing jsonGenerator.writeStringField("addressLine", student.getAddress().getAddressLine()); jsonGenerator.writeStringField("city", student.getAddress().getCity()); jsonGenerator.writeNumberField("zipCode", student.getAddress().getZipCode()); jsonGenerator.writeEndObject(); // address object completed jsonGenerator.writeArrayFieldStart("phoneNumbers"); for (long num : student.getPhoneNumbers()) jsonGenerator.writeNumber(num); jsonGenerator.writeEndArray(); // start array writing for cities jsonGenerator.writeArrayFieldStart("cities"); for (String city : student.getCities()) jsonGenerator.writeString(city); // closing cities array jsonGenerator.writeEndArray(); jsonGenerator.writeObjectFieldStart("properties"); SetkeySet = student.getProperties().keySet(); for (String key : keySet) < String value = student.getProperties().get(key); jsonGenerator.writeStringField(key, value); >// End of properties writing jsonGenerator.writeEndObject(); //End root object writing jsonGenerator.writeEndObject(); jsonGenerator.flush(); jsonGenerator.close(); > catch (IOException ex) < ex.printStackTrace(); >> public static Student sampleStudentObject() < Student student = new Student(); student.setRollNumber(11); student.setFirstName("Saurabh"); student.setLastName("Gupta"); student.setPhoneNumbers(new long[] < 2233445566L, 3344556677L >); Address add = new Address(); add.setAddressLine("Lake Union Hill Way"); add.setCity("Atlanta"); add.setState("GA"); add.setZipCode(50005); student.setAddress(add); List cities = new ArrayList(); cities.add("Dallas"); cities.add("San Antonio"); cities.add("Irving"); student.setCities(cities); Map props = new HashMap(); props.put("age", "34 years"); props.put("interst", "Math"); props.put("play", "Badminton"); student.setProperties(props); return student; > >

Model Object

Student and Address classes are required to execute these code

package test.facingissesonit.json.jacson; import java.util.Arrays; import java.util.List; import java.util.Map; public class Student < private int rollNumber; private String firstName; private String lastName; private boolean permanent; private Address address; private long[] phoneNumbers; private Listcities; private Map properties; @Override public String toString() < StringBuffer sb=new StringBuffer(); sb.append("==============Student Information================\n"); sb.append("rollNumber=").append(rollNumber).append("\n"); sb.append("firstName=").append(firstName).append("\n"); sb.append("lastName=").append(lastName).append("\n"); sb.append("permanent=").append(permanent).append("\n"); sb.append("adress=").append(address).append("\n"); sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n"); sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n"); sb.append("properties=").append(properties).append("\n"); return sb.toString(); >public int getRollNumber() < return rollNumber; >public void setRollNumber(int rollNumber) < this.rollNumber = rollNumber; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >public boolean isPermanent() < return permanent; >public void setPermanent(boolean permanent) < this.permanent = permanent; >public Address getAddress() < return address; >public void setAddress(Address address) < this.address = address; >public long[] getPhoneNumbers() < return phoneNumbers; >public void setPhoneNumbers(long[] phoneNumbers) < this.phoneNumbers = phoneNumbers; >public List getCities() < return cities; >public void setCities(List cities) < this.cities = cities; >public Map getProperties() < return properties; >public void setProperties(Map properties) < this.properties = properties; >>
package test.facingissesonit.json.jacson; public class Address < private String addressLine; private String city; private String state; private int zipCode; @Override public String toString() < StringBuffer sb=new StringBuffer(); sb.append("AddressLine=").append(addressLine).append("\n"); sb.append("city=").append(city).append("\n"); sb.append("state=").append(state).append("\n"); sb.append("zipCode=").append(zipCode).append("\n"); return sb.toString(); >public String getAddressLine() < return addressLine; >public void setAddressLine(String addressLine) < this.addressLine = addressLine; >public String getCity() < return city; >public void setCity(String city) < this.city = city; >public String getState() < return state; >public void setState(String state) < this.state = state; >public int getZipCode() < return zipCode; >public void setZipCode(int zipCode) < this.zipCode = zipCode; >>

Output

Generated output on Student_data.txt file

< "rollNumber" : 11, "firstName" : "Saurabh", "lastName" : "Gupta", "permanent" : false, "address" : < "addressLine" : "Lake Union Hill Way", "city" : "Atlanta", "zipCode" : 50005 >, "phoneNumbers" : [ 2233445566, 3344556677 ], "cities" : [ "Dallas", "San Antonio", "Irving" ], "properties" : < "play" : "Badminton", "interst" : "Math", "age" : "34 years" >>

More Sample Code

For more java and JDBC codes follow below links

Источник

Оцените статью