JSON to string/int conversion using jsonbody request - java

Hello im trying to use a post request to pull in strings and integers in the body of the request ,what is the best way to do this ?
entering something like this in a rest client for example :
{
"name":"ExName",
"reading":"100"
}
#POST
#Path("/SetFeeds")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#JsonCreator
//public String setFeed(#PathParam("name")String name2, #QueryParam("name") String name,#Context UriInfo uriInfo,String jsonBody){
public String setFeed(String jsonBody,#Context UriInfo uriInfo){
MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
String query = uriInfo.getRequestUri().getQuery();
String response = queryParams.getFirst("name");
System.out.println(response);
//System.out.println(name2);
//JSONObject jsonObject = new JSONObject();
//JSONObject nodeStats = name.get(getJSONObject("name"));
// Getting the value of a attribute in a JSONObject
//String sSDR = actualObj.getString("sdr");
//FeedObjects x=new FeedObjects();
//System.out.println(x.getName());
return response;
}

You might want to consider creating a class that you want and use gson library to convert object to json.
I think it will be much more easier with less "dirty work".
Check it here:
https://github.com/google/gson
Here's an example from: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(json);
}
}

Related

How to make two classes to work together and return it as JSON

My plan is to make a JSON results by my database. What I mean is that I have made a Class where I connect to a API (etc. TMDB) and take the information I need.
public class MovieDataBase {
Attributes att = new Attributes(); //A klass where I have setter-getter
//methods for titel, overview, vote, release.
public String searchMovie(String filmtitel) {
HttpResponse<JsonNode> response;
try {
response = Unirest.get("http://api.themoviedb.org/3/search/movie")
.queryString("api_key", "123")
.queryString("query", filmtitel)
.asJson();
JsonNode json = response.getBody();
JSONObject envelope = json.getObject();
JSONArray results = envelope.getJSONArray("results");
filmtitel += att.title = results.getJSONObject(0).getString("title");
filmtitel += att.release = results.getJSONObject(0).getString("release_date");
filmtitel += att.vote = results.getJSONObject(0).getInt("vote_average");
filmtitel += att.overview = results.getJSONObject(0).getString("overview");
return filmtitel
}
catch (JSONException e) {
and I also have a get method where I want to create a JSON construction of the program to easier use it in the future (for html)
public static void main(String[] args) {
Gson gson = new Gson();
setPort(8080);
Youtube yt = new Youtube();
MovieDataBase mdb = new MovieDataBase();
get("/search/:movie", (req, res) -> {
String movie = req.queryParams(":movie");
String movies = mdb.searchMovie(movie);
String json = att.title + att.release + att.vote + att.vote + att.overview
json = gson.toJson(json);
return json
});
This did not work. I'm getting a null when I'm running it, not a error but only a null. So I have to combine String movies = mdb.searchMovie(movie); with the String Json and then make it look like a json, but I don't know if that's right.

can't fetch json object with correct format

Suppose I am fetching from an api some json array as so
[{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]
I want to retrieve this json as an Some object from URL_Some url
public class Some implements Serializable {
private String id;
private String title;
private String description;
private String vote;
private String created_at;
private String updated_at;
}//with all getters and setters
.
public List<Some> getSome() throws IOException {
try {
HttpRequest request = execute(HttpRequest.get(URL_Some));
SomeWrapper response = fromJson(request, SomeWrapper.class);
Field[] fields = response.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
try {
Log.i("TAG", (String) fields[i].get(response));
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Log.i("TAG", fields[i].getName());
}
if (response != null && response.results != null)
return response.results;
return Collections.emptyList();
} catch (HttpRequestException e) {
throw e.getCause();
}
}
and SomeWrapper is simply
private static class SomeWrapper {
private List<Some> results;
}
The problem is that I keep on getting this message
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
PS : I use
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
Your json should actually be like this:
{"results": [{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]}
Gson will try to parse the json and create a SomeWrapper object. This alone tells Gson he will wait for a json with this format {...} since he's expecting an object. However you passed an array instead, that's why it complains about expecting BEGIN_OBJECT ({) but getting BEGIN_ARRAY instead ([). After that, it will expect this json object to have a results field, which will hold an array of objects.
You can create List<Some> directly without the need of a wrapper class however. To do so do this instead:
Type type= new TypeToken<List<Some>>() {}.getType();
List<Some> someList = new GsonBuilder().create().fromJson(jsonArray, type);
In this case, you can use the original json array you posted.
The JSON you posted is a JSON array, which is indicated by the squared brackets around it: [ ].
You'd have to read the first object from the JSON array.
I personally use the org.json packages for Android JSON and parse my JSON in a manner like this:
private void parseJSON(String jsonString) {
JSONArray json;
try {
json = new JSONArray(jsonString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String id = jsonObject.getString("id");
} catch (JSONException jsonex) {
jsonex.printStackTrace();
}
}
If you've got multiple JSON objects in your array you can iterate over them by using a simple for loop (not for each!)

Parse json array android

Hi i'm trying to parse json array from this url. The json array looks like this.
[
{
"id":1,
"introtext":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430\u0442\u0430 \u0435 \u043e\u0434 \u0430\u043c\u0435\u0440\u0438\u043a\u0430\u043d\u0441\u043a\u043e \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0441\u0442\u0432\u043e \u0432\u043e \u0431\u0435\u043b\u0430 \u0431\u043e\u0458\u0430 \u0434\u043e\u043b\u0433\u0430 \u043e\u043a\u043e\u043b\u0443 8,5 \u043c\u0435\u0442\u0440\u0438. \u041e\u043f\u0440\u0435\u043c\u0435\u043d\u0430 \u0435 \u0441\u043e \u043a\u043b\u0438\u043c\u0430 \u0440\u0435\u0434, \u0422\u0412, \u0414\u0412\u0414 \u0438 \u0431\u0430\u0440. \u041c\u043e\u0436\u0430\u0442 \u0434\u0430 \u0441\u0435 \u0432\u043e\u0437\u0430\u0442 \u0434\u043e 9 \u043b\u0438\u0446\u0430. \u0421\u0435 \u0438\u0437\u043d\u0430\u0458\u043c\u0443\u0432\u0430 \u0441\u043e \u043d\u0430\u0448 \u0448\u043e\u0444\u0435\u0440.\n{AdmirorGallery}..\/katalog\/prevoz\/limo-servis-jasmina\/linkoln\/{\/AdmirorGallery}\n\u00a0",
"image":"http:\/\/zasvadba.mk\/media\/k2\/items\/cache\/787ae9ec9023a82f5aa7e4c1a64f73cb_S.jpg",
"title":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430 \u041b\u0438\u043d\u043a\u043e\u043b\u043d",
"catid":"20",
"alias":"\u043b\u0438\u043c\u0443\u0437\u0438\u043d\u0430-\u043b\u0438\u043d\u043a\u043e\u043b\u043d-\u043b\u0438\u043c\u043e-\u0441\u0435\u0440\u0432\u0438\u0441-\u0458\u0430\u0441\u043c\u0438\u043d\u0430"
}
]
I'm doing this in my java class
try {
JSONfunctions j=new JSONfunctions();
JSONObject json = j.getJSONfromURL(url);
Log.i("log_tag", json.toString());
String jsonvalues = json.getString("id");
Log.i("DARE", jsonvalues);
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
}
But it doesn't work, can anybody help me parse my json array
you will need to make two changes in your current code according to string u have posted here for parsing as Json :
First : change the return type of getJSONfromURL method to JSONArray and return JSONArray from it instead of JSONObject
For example :
public JSONArray getJSONfromURL(String url){
String str_response="response from server";
// convert response to JSONArray
JSONArray json_Array=new JSONArray(str_response);
return json_Array; //<< retun jsonArray
}
Second : change your code as for getting value from JsonArray :
try {
JSONfunctions j=new JSONfunctions();
JSONArray jArray = j.getJSONfromURL(url);
Log.i("log_tag", jArray.toString());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String jsonvalues = json_data.getString("id");
// .. get all value here
Log.i("DARE", jsonvalues);
}
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
Of course it doesn't work! You should use json.getJSONArray(...) method for parsing arrays in Json :)
You can Easily do it using gson library.
Here is the code sample:
Your Entity Class will like:
public class ResponseEntity {
#SerializedName("id")
public int id;
#SerializedName("introtext")
public String introtext;
#SerializedName("image")
public String image;
#SerializedName("title")
public String title;
#SerializedName("catid")
public String catid;
#SerializedName("alias")
public String alias;
}
Now Convert this json Array using GSON library.
Gson gson=new Gson();
ResponseEntity[] entities = gson.fromJson(yourResponseAsString.toString(),
ResponseEntity[].class);
Now you have the entity array at entities.
Thanks.

Convert Json to an specific Class

i'm trying to retrieve text from wikipedia to use on an Android app. I'm using Java.
The first thing I want to do is to retrieve the sections from an specific article, show them to the user and, when the user clicks on one section, get the section text with another http request.
So, the two requests are these:
http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Valencia_Cathedral&prop=sections
and then this one:
http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Valencia_Cathedral&prop=text&section=1
My question is: What kind of java objects should I create to store the information and then convert it to these classes using .fromJSON()?
Thanks to #NathanZ, I created these two classes:
public class WikiResponseSections {
String title;
List<Section> sections;
}
public class Section {
int toclevel;
String level;
String line;
String number;
String index;
String fromtitle;
int byteoffset;
String anchor;
}
But, when I convert the HTTP response to these objets by Gson, and try to read the value of the field 'title' there's an error that triggers: JavaNullPointerException.
Here's my code for the conversion:
InputStream stream = null;
try {
stream = entity.getContent();
} catch (IllegalStateException e) {
Log.e("Stream","ERROR illegalstateexception");
} catch (IOException e) {
Log.e("Stream","ERROR exception");
}
reader = new BufferedReader(new InputStreamReader(stream));
GsonBuilder bldr = new GsonBuilder();
Gson gson = bldr.create();
WikiResponse = gson.fromJson(reader, WikiResponseSections.class);
if (WikiResponse != null){
Log.i("WikiResponse",WikiResponse.getTitle()); //The error triggers HERE
publishProgress();
}
else
Log.i("WikiResponse","NULL");
}
Thanks for your help again
You can use the Google's Gson library.
It works like this:
InputStream source = ...; // your code to get the Json from a url
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
MyResponse response = gson.fromJson(reader, MyResponse.class);
Where MyResponse is your object. When you create MyResponse, give your fields the same name and type as the Json's fields
MyResponse class can be as follows:
public class MyResponse{
String title;
ArrayList<sections>;
}
public class sections{
int toclevel;
String level;
String line;
String number;
String fromtitle;
long byteoffset;
String anchor;
}
public class WikiResponseParse{
Parse parse;
public class Parse{
String title, text;
}
}
If you can't use the json fields name because it's not Java compliant:
Add the following import:
import com.google.gson.annotations.SerializedName;
and in your class:
#SerializedName("*")
public String star;

Creating a JSON object

I am making a JSON request to server using Java. Here is the following parameters.
{method:'SearchBySearchConfiguration',params:[{{SearchCriteria:'%arriva',
IsAccountSearch:true,IsContactSearch:false,SearchByName:true,SearchByAddress:false
CRMTextValues:[], CRMCurrencyValues:[]}]}
I could do this way.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
How do I add the rest of params, in name-value pair to JSON object?
Thanks in advance!
One way I can think of is using the org.json library. I wrote a sample to build part of your request object:
public static void main(String[] args) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "SearchBySearchConfiguration");
JSONArray jsonArray = new JSONArray();
JSONObject innerRecord = new JSONObject();
innerRecord.put("SearchCriteria", "%arriva");
innerRecord.put("IsAccountSearch", true);
jsonArray.put(innerRecord);
jsonObject.put("params",jsonArray);
System.out.println("jsonObject :"+jsonObject);
}
The output is :
jsonObject :{"method":"SearchBySearchConfiguration","params":[{"IsAccountSearch":true,"SearchCriteria":"%arriva"}]}
Another technique would be to build Java objects that resemble your request structure. You can then convert it into json using Jackson library's ObjectMapper class.
In both cases once you get the json string, you can directly write it into the request body.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
JSONArray paramsArr = new JSONArray();
JSONObject arrobj = new JSONOject();
arrobj.put("SearchCriteria","%arriva");
arrobj.put("IsAccountSearch","true");
arrobj.put("IsContactSearch","false");
arrobj.put("SearchByName","true");
arrobj.put("SearchByAddress","false");
arrobj.put("CRMTextValues",new JSONArray());
arrobj.put("CRMCurrencyValues",new JSONArray());
paramsArr.put(arrobj);
json.put("params",paramsArr);
The you can create JSONArray and put that array in JSONObject
Its Better to use gson for this.
First you need to create classs with following members :
public class TestClass{
private String method;
private ParamClass params;
}
public class ParamClass{
private String SearchCriteria;
private boolean IsAccountSearch;
private boolean IsContactSearch;
private boolean SearchByName;
private boolean SearchByAddress;
private String[] CRMTextValues;
private String[] CRMCurrencyValues;
}
Usage :
Serializing :
Gson gson = new Gson();
String jsonString = gson.toJson(testClassObject);
Deserializing :
Gson gson = new Gson();
TestClass testClassObject = gson.fromJson(jsonString , TestClass.class);
See this below example, where a JSONArray is returned and then how i am converting it in JSONObject form...
public JSONArray go() throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx");
return json;
}
JSONArray jarr;
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){}
Jackson is a very efficient to do JSON Parsing
See this link:
http://jackson.codehaus.org/
Gson is provided by google which is also a good way to handle JSON.
To add params, JSONArray is used.
Inside params, we use JSONObject to add data such as SearchByAddress, IsAccountSearch ..etc.
Reference http://www.mkyong.com/java/json-simple-example-read-and-write-json/
package com.test.json;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("method", "SearchBySearchConfiguration");
JSONArray list = new JSONArray();
JSONObject innerObj = new JSONObject();
innerObj.put("SearchCriteria","%arriva" );
innerObj.put("IsAccountSearch",true);
innerObj.put("IsContactSearch",false);
innerObj.put("SearchByName",true);
innerObj.put("SearchByAddress",false);
innerObj.put("CRMTextValues",new JSONArray());
innerObj.put("CRMCurrencyValues",new JSONArray());
list.add(innerObj);
obj.put("params", list);
System.out.print(obj);
}
}

Categories

Resources