how to send multiple same objects using json in java? - java

i write java code for sending multiple json same objects in java as below..
public class Book {
private String name;
private int prize;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrize() {
return prize;
}
public void setPrize(int prize) {
this.prize = prize;
}
}
public class Books {
List<Book> books;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
#Path("books")
public interface BookIntf {
#Path("/book")
#POST
#Produces({ "application/xml", "application/json" })
#Consumes({ "application/xml", "application/json" })
public Response addBooks(Books books);
}
public class BookServiceImpl implements BookIntf {
public Response addBooks(Books books) {
String status = null;
JSONObject soapDatainJsonObject = null;
String jsontext = null;
try {
BookDao iotdao = new BookDao();
status = iotdao.addBooks(books);
} catch (Exception localException) {
status = "failed in Service layer";
}
return Response.ok().type(MediaType.APPLICATION_JSON).entity(jsontext).build();
}
}
public class BookDao {
public String addBooks(Books books) {
Session aoSession = MDHibernateUtil.getSessionFactory().openSession();
Transaction addObjectTx = null;
String XMLStatusString = null;
StringBuffer sb = new StringBuffer();
try {
addObjectTx = aoSession.beginTransaction();
List inPutAnalytics = books.getBooks();
Iterator itrIPAnalytics = inPutAnalytics.iterator();
while (itrIPAnalytics.hasNext()) {
Book iotAnalyticPOJO = (Book) itrIPAnalytics.next();
String bookName = iotAnalyticPOJO.getName();
int price = iotAnalyticPOJO.getPrize();
System.out.println("bookName:"+bookName);
System.out.println("price: "+price);
}
} catch (Exception localexception) {
if (addObjectTx != null)
addObjectTx.rollback();
} finally {
aoSession.close();
}
return XMLStatusString;
}
}
can you please tell me is their any mistakes in above code. and url for that is:-
http://localhost:8081/Smarter/services/books/book
Request Body:-
{
"books":
[
{
"name":"mani",
"prize":120
},
{
"name":"nani",
"prize":1240
}
]
}
The Error is 415 Unsupported Media Type...
can you please tell me how to pass multiple same objects in java using json.
Thanks..

Related

How to parse JSON Text in Java [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I have the following JSON text. How can I parse it to get response-code, response, result, DISPLAYNAME ,AVAILABILITYSEVERITY, RESOURCEID , ETC?
{
"response-code":"4000",
"response":
{
"result":
[
{
"DISPLAYNAME":"Backup Server",
"AVAILABILITYSEVERITY":"5",
"RESOURCEID":"10002239110",
"TYPE":"SUN",
"SHORTMESSAGE":"Clear"
}
]
,"uri":"/json/ListAlarms"
}
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public static void main(String[] args) {
final String json = "{ \"response-code\":\"4000\", \"response\": { \"result\": [ { \"DISPLAYNAME\":\"Backup Server\", \"AVAILABILITYSEVERITY\":\"5\", \"RESOURCEID\":\"10002239110\", \"TYPE\":\"SUN\", \"SHORTMESSAGE\":\"Clear\" } ] ,\"uri\":\"/json/ListAlarms\" } }";
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode obj = mapper.readTree(json);
System.out.println(obj.get("response-code"));
JsonNode response = obj.get("response");
JsonNode firstResult = response.get("result").get(0);
System.out.println(firstResult.get("DISPLAYNAME"));
System.out.println(firstResult.get("AVAILABILITYSEVERITY"));
System.out.println(firstResult.get("RESOURCEID"));
System.out.println(firstResult.get("TYPE"));
System.out.println(firstResult.get("SHORTMESSAGE"));
System.out.println(response.get("uri"));
} catch (IOException e) {
e.printStackTrace();
}
}
output
"4000"
"Backup Server"
"5"
"10002239110"
"SUN"
"Clear"
"/json/ListAlarms"
another approach only if the json has fixed structure, is to build objects to represent the json structure and use jackson to cast that json to a java object, like
class JsonObj {
#JsonProperty("response-code")
private long responseCode;
private ResponseObj response;
public long getResponseCode() {
return responseCode;
}
public void setResponseCode(long responseCode) {
this.responseCode = responseCode;
}
public ResponseObj getResponse() {
return response;
}
public void setResponse(ResponseObj response) {
this.response = response;
}
}
class ResponseObj {
private ArrayList<ResultObj> result;
private String uri;
public ArrayList<ResultObj> getResult() {
return result;
}
public void setResult(ArrayList<ResultObj> result) {
this.result = result;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
class ResultObj {
#JsonProperty("DISPLAYNAME")
private String displayName;
#JsonProperty("TYPE")
private String type;
#JsonProperty("AVAILABILITYSEVERITY")
private int availabilitySeverity;
#JsonProperty("RESOURCEID")
private String resourceId;
#JsonProperty("SHORTMESSAGE")
private String shortMessage;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAvailabilitySeverity() {
return availabilitySeverity;
}
public void setAvailabilitySeverity(int availabilitySeverity) {
this.availabilitySeverity = availabilitySeverity;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getShortMessage() {
return shortMessage;
}
public void setShortMessage(String shortMessage) {
this.shortMessage = shortMessage;
}
}
and then, access the values like that
JsonObj jsonObj = mapper.readValue(json, JsonObj.class);
System.out.println(jsonObj.getResponseCode());
ResponseObj response = jsonObj.getResponse();
ResultObj firstResult = response.getResult().get(0);
System.out.println(firstResult.getDisplayName());
System.out.println(firstResult.getAvailabilitySeverity());
System.out.println(firstResult.getResourceId());
System.out.println(firstResult.getType());
System.out.println(firstResult.getShortMessage());
System.out.println(response.getUri());
the output is the same...

parsing multi nested json with GSON

I have to parse the json file into text file, Sample json file as below,
{
"link":"https://xxx.nt",
"liveChannels":[
{
"name":"Sony TV",
"id":1004,
"link":"https://xxx.nt",
"decryptionTicket":"https://xxxy.nt",
"viewLevel":"Too High",
"programs":
{
"totalItems":1,
"programs":[
{
"name":"Live or die",
"id":1000000000,
"catchUp":["FUN"],
"startOver":["Again"]
}
]
}
}
]
}
I have used GSON to parse the file by creating the below java classes.
Channel
LiveChannel
programs
subprograms
Channel.java
public class channel
{
String link = null;
ArrayList<liveChannels> liveChannels;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public ArrayList<liveChannels> getliveChannels() {
return liveChannels;
}
public void setliveChannels(ArrayList<liveChannels> liveChannels) {
this.liveChannels = liveChannels;
}
}
livechannel.java
public class liveChannels {
String name = null;
int id;
String link = null;
String decryptionTicket = null;
String viewLevel = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDecryptionTicket() {
return decryptionTicket;
}
public void setDecryptionTicket(String decryptionTicket) {
this.decryptionTicket = decryptionTicket;
}
public String getViewLevel() {
return viewLevel;
}
public void setViewLevel(String viewLevel) {
this.viewLevel = viewLevel;
}
}
After this how to parse the logic from program onwards.
"programs":
{
"totalItems":1,
program.java
public class programs {
ArrayList<sub_programs> sub_programs;
int totalItems;
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
public ArrayList<sub_programs> getProgramsDetails() {
return sub_programs;
}
public void setProgramsDetails(ArrayList<sub_programs> sub_programs) {
this.sub_programs = sub_programs;
}
}
sub_program.java
public class sub_programs {
String name = null;
int id;
String catchUp = null;
String startOver = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCatchUp() {
return catchUp;
}
public void setCatchUp(String catchUp) {
this.catchUp = catchUp;
}
public String getStartOver() {
return startOver;
}
public void setStartOver(String startOver) {
this.startOver = startOver;
}
}
and main look like below,
public static void main(String[] args) throws IOException
{
Gson gson = new Gson();
String contents = FileUtils.readFileToString(
new File("C:/sample.json"), "UTF-8");
channel channelHeader = gson.fromJson(contents, channel.class);
System.out.println("Channel Information --->");
System.out.println("Channel Link: " + channelHeader.getLink());
ArrayList<liveChannels> liveChannels = channelHeader.getliveChannels();
for (int i = 0; i < liveChannels.size(); i++) {
System.out.println("liveChannels Detail --->");
liveChannels liveChannelsDetail = liveChannels.get(i);
System.out.println("Channel Name : " + liveChannelsDetail.getName());
System.out.println("Channel ID : " + liveChannelsDetail.getId());
System.out.println("Channel Description Ticket: " + liveChannelsDetail.getDecryptionTicket());
System.out.println("Channel View Level : " + liveChannelsDetail.getViewLevel());
}
}
}
Could anyone please help to get the logic to parse the program from livechannel class onwards.
As programs is not an array list , What else would be an other way around to get the values.
You are missing the programs object in your liveChannels class.
public class liveChannels {
String name = null;
int id;
String link = null;
String decryptionTicket = null;
String viewLevel = null;
programs programs;
public void setPrograms (programs programs) {
this.programs = programs;
}
public programs getPrograms() {
return programs;
}
...
}
And then in your programs class, you will need to rename the sub_programs field to programs
public class programs {
ArrayList<sub_programs> programs;
...
}
As an aside, your class naming does not follow Java standards and is considered bad practice. Your classes should be named as such:
Channel
LiveChannel
Program
SubProgram
Note that this will not affect GSON's ability to parse your documents as GSON cares more about the property name than it does the actual class name of the field.

Parsing JSON in Android, not getting value

I am able to parse everything i need, except for the target_id's in the field_exercis_arc. I get the nid, title and body. Not sure how to get the id's in the field_exercis_arc.
The JSON
[{
"nid": "26",
"title": "Question test",
"body": "xcvxcv",
"field_exercis_arc": ["25","27"]
}]
The Code
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ExerciseModel> exerciseModelList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
title_exi = finalObject.getString("title");
text_exi = finalObject.getString("body");
//This part is working.
ExerciseModel exerciseModel = new ExerciseModel();
exerciseModel.setTitle(finalObject.getString("title"));
exerciseModel.setNid(finalObject.getInt("nid"));
exerciseModel.setBody(finalObject.getString("body"));
//Problem with this part, not getting the target_id's.
List<ExerciseModel.Exer> exerList = new ArrayList<>();
for(int j=0; j<finalObject.getJSONArray("field_exercis_arc").length(); j++){
ExerciseModel.Exer exercis = new ExerciseModel.Exer();
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getJSONObject(j).getString("target_id"));
exerList.add(exercis);
}
exerciseModel.setExerList(exerList);
exerciseModelList.add(exerciseModel);
mDB.saveRecordEX(exerciseModel);
}
The model for the field_exercis_arc and target_id's fields
private List<Exer> exerList;
public List<Exer> getExerList() {
return exerList;
}
public void setExerList(List<Exer> exerList) {
this.exerList = exerList;
}
public static class Exer{
private String target_id;
public String getTarget_id() {
return target_id;
}
public void setTarget_id(String target_id) {
this.target_id = target_id;
}
}
Thanks in advance
I recommend you to use GSON library to get result from JSON. For that you will need Java class in order to parse result to object. For this you can use JSON to Java Class conversion here.
For you example classes would be:
public class Und
{
private String value;
public String getValue() { return this.value; }
public void setValue(String value) { this.value = value; }
}
public class Body
{
private ArrayList<Und> und;
public ArrayList<Und> getUnd() { return this.und; }
public void setUnd(ArrayList<Und> und) { this.und = und; }
}
public class Und2
{
private String target_id;
public String getTargetId() { return this.target_id; }
public void setTargetId(String target_id) { this.target_id = target_id; }
}
public class FieldExercisArc
{
private ArrayList<Und2> und;
public ArrayList<Und2> getUnd() { return this.und; }
public void setUnd(ArrayList<Und2> und) { this.und = und; }
}
public class RootObject
{
private String vid;
public String getVid() { return this.vid; }
public void setVid(String vid) { this.vid = vid; }
private String uid;
public String getUid() { return this.uid; }
public void setUid(String uid) { this.uid = uid; }
private String title;
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
private Body body;
public Body getBody() { return this.body; }
public void setBody(Body body) { this.body = body; }
private FieldExercisArc field_exercis_arc;
public FieldExercisArc getFieldExercisArc() { return this.field_exercis_arc; }
public void setFieldExercisArc(FieldExercisArc field_exercis_arc) { this.field_exercis_arc = field_exercis_arc; }
private String cid;
public String getCid() { return this.cid; }
public void setCid(String cid) { this.cid = cid; }
private String last_comment_timestamp;
public String getLastCommentTimestamp() { return this.last_comment_timestamp; }
public void setLastCommentTimestamp(String last_comment_timestamp) { this.last_comment_timestamp = last_comment_timestamp; }
}
You can convert result to RootObject. Fox example:
String json = "{\"vid\": \"26\",\"uid\": \"1\",\"title\": \"Question test\",\"body\": {\"und\": [{\"value\": \"xcvxcv\"}]},\"field_exercis_arc\": {\"und\": [{\"target_id\": \"25\"},{\"target_id\":\"27\"}]},\"cid\": \"0\",\"last_comment_timestamp\": \"1472217577\"}";
RootObject object = new Gson().fromJson(json, RootObject.class);
System.out.println("Title is: "+object.getTitle() );
Result is:
Title is: Question test
After this you can use your object to get any value from your JSON.
Also you should know that your JSON is not valid. You have commas on two places that should not exists. In string i gave you above those are fixed. You should check you JSON with: JSON Formatter
Use below code :
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getString(j));
JsonArray fieldArray=yourJsonObject.getJsonArray("field_exercis_arc");
for(int i=0;i<fieldArray.length;i++){
fieldArray.getString(i);
}
TO the parse the JSON you have to do it like this.
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
String title = finalObject.getString("title");
String body = finalObject.getString("body");
JSONArray arr = finalObject.getJSONArray("field_exercis_arc");
for(int x=0; x < arr.length(); x++){
String val = arr.getString(x);
}
}

POST returned a response status of 500 Internal Server Error in RESTful client communication

Folks,
I am working with the RESTful webservice in java and it causing the 500 error while communicating from the Java application
I referred this tutorial to do the same
implementing RESTful Web Services in Java
here is the RESTful webservice
#Path("WebTest")
#Produces("application/json")
public class WebTestResource {
private TreeMap<Integer, BookDemo> bookMap = new TreeMap<Integer, BookDemo>();
public WebTestResource() {
}
#GET
public List<BookDemo> getBooks() {
List<BookDemo> books = new ArrayList<BookDemo>();
books.addAll(bookMap.values());
return books;
}
#GET
#Path("{id}")
public BookDemo getBook(#PathParam("id") int bookId) {
return bookMap.get(bookId);
}
#POST
#Path("add")
#Produces("text/plain")
#Consumes("application/json")
public String addBook(BookDemo book) {
int id = bookMap.size();
try{
book.setId(id);
bookMap.put(id, book);
String strFilePath = "D:\\Java™\\RESTful\\test.txt";
FileWriter file= null;
try {
file = new FileWriter(strFilePath);
file.write(book.getBookName());
} catch (IOException ex) {
Logger.getLogger(WebTestResource.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
file.flush();
file.close();
} catch (IOException ex) {
Logger.getLogger(WebTestResource.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
catch(Exception ex){
}
return "Book \"" + book.getBookName() + "\" added with Id " + id;
}
}
Webservice Client to the java application
public class Restful {
private WebResource webResource;
private Client client;
private static final String BASE_URI = "http://localhost:8050/WebRestfulAppTest/services";
public Restful() {
com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
client = Client.create(config);
webResource = client.resource(BASE_URI).path("WebTest");
}
public <T> T getBook(Class<T> responseType, String id) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
return resource.get(responseType);
}
public String addBook(Object requestEntity) throws UniformInterfaceException {
return webResource.path("add").type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(String.class, requestEntity);
}
public <T> T getBooks(Class<T> responseType) throws UniformInterfaceException {
WebResource resource = webResource;
return resource.get(responseType);
}
public void close() {
client.destroy();
}
}
POJO
#XmlRootElement(name = "BookDemo")
public class BookDemo {
private int id;
private String bookName;
private String bookAuthor;
private String bookISBN;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
public String getBookISBN() {
return bookISBN;
}
public void setBookISBN(String bookISBN) {
this.bookISBN = bookISBN;
}
}
main()
public class GetCallService {
static Restful objRestful = new Restful();
public static void main(String[] args){
try{
BookDemo book = new BookDemo();
book.setBookAuthor("ABC");
book.setBookName("Introduction to RESTful Web Services Example test application");
book.setBookISBN("ISBN 10: 0-596-52926-0");
objRestful.addBook(book);
BookDemo book1 = new BookDemo();
book1.setBookAuthor("XYZ");
book1.setBookName("RESTfull web");
book1.setBookISBN("ISBN 10: 0-596-52926-0 Prajwal");
objRestful.addBook(book1);
}
catch(Exception ex){
ErrorLog.errorLog(ex);
}
}
}
Exception
ex = (com.sun.jersey.api.client.UniformInterfaceException)
com.sun.jersey.api.client.UniformInterfaceException: POST
http://localhost:8050/WebRestfulAppTest/services/WebTest/add returned
a response status of 500 Internal Server Error
there is an Exception in the web services add :
catch(Exception ex){
ex.printStackTrace();
}

JSON mapping to Java returning null value

I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.

Categories