Parsing Representation in Restlet - java

I am getting JSONException when I try to put in JSONObject.
#Post
public String someCode(Representation rep) throws ResourceException{
try {
rep.getText();
} catch (IOException e) {
LOGGER.error("Error in receiving data from Social", e);
}
try {
JSONObject json = new JSONObject(rep);
String username = json.getString("username");
String password = json.getString("password");
String firstname = json.getString("firstname");
String lastname = json.getString("lastname");
String phone = json.getString("phone");
String email = json.getString("email");
LOGGER.info("username: "+username); //JsonException
LOGGER.info("password: "+password);
LOGGER.info("firstname: "+firstname);
LOGGER.info("lastname: "+lastname);
LOGGER.info("phone: "+phone);
LOGGER.info("email: "+email);
} catch (JSONException e) {
e.printStackTrace();
}
return "200";
}
ERROR LOG:
org.json.JSONException: JSONObject["username"] not found.
at org.json.JSONObject.get(JSONObject.java:516)
at org.json.JSONObject.getString(JSONObject.java:687)
NOTE:
When I try to print rep.getText(), I get the following data:
username=user1&password=222222&firstname=Kevin&lastname=Tak&phone=444444444&email=tka%40gmail.com

Your rep object isn't a JSON object. I actually think that when you pass it to JSONObject(), it only captures a weird string. I suggest to parse it into an array :
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = rep.getText();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}

What you are Receiving in the POST is HTTP Form encoded data not JSON.
Restlet can and does handle these objects natively providing the Form object to interact with them. rather than new JSONObject(String) try new Form(String), for example:
String data = rep.getText();
Form form = new Form(data);
String username = form.getFirstValue("username");
I leave the remainder as an exercise to the reader.
Alternatively you will need to adjust the client submitting the data to encode it in JSON see http://www.json.org/ for the description of this syntax.
For reference the Form class is org.restlet.data.Form in the core Restlet library.

Related

JAVA get Byte[] nested in JSONObject

i need to get a response from a org.json.JSONObject (args).
new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject response = new JSONObject(args[0].toString());
JSONObject data = (JSONObject) response.get("data");
Object defaultResponce = data.get("default");
Log.d(TAG, defaultResponce + "");
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
Object defaultResponce = data.get("default"); equates to a 10 character, String "[B#ffc06c8"
The following image is the args response in the debugger. i need to get the pointed out value.
how do i retreive the value as it in in the debugger?
I think you got mixed up a bit...
Object defaultResponce = data.get("default");
Log.d(TAG, defaultResponce + "");
--> The Log.d prints the reference (defaultResponce + "" converts the byte[] to string). Is this why you think it's a string?
check out if defaultResponce is an instance of byte[] or whatever you are looking for.
Anyway, you can always use reflection to get to the field you want if the standard API doesn't return what you are looking for.

Unable to split json response?

This is my method
public String buildJsonData(String username , String message)
{
JsonObject jsonObject = Json.createObjectBuilder().add("Username",username+":"+message).build();
StringWriter stringWriter = new StringWriter();
try(JsonWriter jsonWriter = Json.createWriter(stringWriter))
{
jsonWriter.write(jsonObject);
}
catch(Exception e)
{
System.out.print("buildJsonData ="+e);
}
return stringWriter.toString();
}
If i input username as john and message as hello.I get output as
{"Username":"john:hello"}
But I want output without braces and doublequotes I want my output as
John:hello
I tried to split it using array[0] but didn't get the output.Is it possible in json to get my desired output(without braces and quotes).
On the sending end, you would put the Username and Message entities into a JSONObject and send the resulting string over the network.
On the receiving end, you would unmarshal the JSON to extract the entities. You can then format them however you like.
Please read about JSON encoding here.
This is a simple example:
private String getResponse(){
JSONObject json = new JSONObject();
try {
json.put("Username", "John");
json.put("Message", "Hellow");
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
private void receiver(){
try {
JSONObject response = new JSONObject(getResponse());
String username = response.getString("Username");
String message = response.getString("Message");
System.out.println(String.format("%s : %s", username,message));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your structure is not really JSON.
A json structure would be like
{
Username : "John",
Message : "Hello"
}
Anf if your want to really use JSON, there is not way to remove braces and quotes. This IS Json.
If you want to output only the part you quoted, store the json value in a variable
String myoutput = stringWriter.toString();
And then remove the parts you don't want with replace() or a regexp
Braces are part of the JSON notation - they indicate an object. If you remove them, then it's not JSON any more. Same goes for double quotes.You are creating your JSON object as:
Json.createObjectBuilder().add("Username",username+":"+message)
This creates an object with property named Username and value john:hello. Again, this is the JSON notation. It's not intended to be read directly, but to facilitate data transfer between applications (on the same or different devices).
If all you want to create is john:message, then instead of creating a JSON object, you should simply do:
String result = username + ":" + message;
return result;

Parse text from webpage in Java (not html)

I am using this code to download a string from a website:
static public String getLast() throws IOException {
String result = "";
URL url = new URL("https://www.bitstamp.net/api/ticker/");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String str;
while ((str = in.readLine()) != null) {
result += str;
}
in.close();
return result;
}
When I print the result of this method, this is what I get:
{"high": "349.90", "last": "335.23", "timestamp": "1384198415", "bid": "335.00", "volume": "33743.67611671", "low": "300.28", "ask": "335.23"}
That's exactly what is shown when you open the URL. This works fine for me, but if there is a more efficient way to do this please let me know.
What I need to extract is 335.23. This number is constantly changing, but the words such as "high", "last", "timestamp", etc always stay the same. I need to extract the 335.23 as a double. Is this possible?
Edit:
SOLVED
String url = "https://www.bitstamp.net/api/ticker/";
try {
JsonFactory factory = new JsonFactory();
JsonParser jParser = factory.createParser(new URL(url));
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("last".equals(fieldname)) {
jParser.nextToken();
System.out.println(jParser.getText());
break;
}
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JarException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is JSON. Use a good parser like Jackson. There are also good Tutorials available.
The response is a json. Use a java JSON Parser and get value for "high" element.
One of the java json parsers is available on (http://www.json.org/java/index.html)
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getString("high");
The data String that you have received is known as JSON encoding. JSON (JavaScript Object Notation) is a lightweight data-interchange format. Use a fine grain simple json encoder and decoder to encode and decode data.

Android application to web server with JSON lib

i have a problem which i cant solve for days.
the String line input is "{"name":"John", "Hobby":"Cycle"}" sent from a JSON from PHP server
The code at android application
public void testFn()
{
try {
while ((line = reader.readLine()) != null) {
String tmp = gson.toJson(line.toString());
JSONObject jobj = (JSONObject)new JSONParser().parse(tmp);
sb.append(jobj.get(1).toString() + "\n");
}
}catch ....
}
i wanted to convert the string received and convert it to a JSONObject / JSONArray which i can retrieve it or display to TextView as a String format. but i keep getting the error of CastException from java.String to JSON.simple.JSONObject..
Hope someone could enlighten me on this
class MyJsonObject{
private String name;
private String Hobby;
MyJsonObject() {
}
}
MyJsonObject obj = new MyJsonObject();
Gson gson = new Gson();
String json = gson.toJson(obj);
(Deserialization)
MyJsonObject obj2 = gson.fromJson(json, MyJsonObject.class);
Try
String str = "{\"name\":\"John\", \"Hobby\":\"Cycle\"}";
//i wrote preceded "\" to very " because it is code format string,
//not came from internet. You can pass direct response from PHP server
try {
JSONObject json = new JSONObject(str);
Log.d("Home",json.getString("name"));
Log.d("Home",json.getString("Hobby"));
} catch (JSONException e1) {
e1.printStackTrace();
}
Basically now i edited my code here
String line = "{"name":"John","Hobby":"Cycle"}";
Object obj=parser.parse(line);
JSONArray array=(JSONArray)obj;
JSONObject obj2 = (JSONObject)array.get(0);
System.out.println(obj2.get("name").toString());
sorry i figured out a way.
Output:
John

Convert Json Array to Java Array

I'm trying to convert this JSON string into an array:
{"result":"success","source":"chat","tag":null,"success":{"message":"%message%","time":%time%,"player":"%player%"}}
I would like to output it like this:
<%player%> %message%
I'm very new to java, I came from PHP where you could just do somthing along the lines of:
$result = json_decode($jsonfile, true);
echo "<".$result['success']['player']."> ".$result['success']['message'];
Output: <%player%> %message%
Is there an easy way to do this in java?
I searched for some similar topics but I didn't really understand them. Could someone explain this to me like I'm 5?
Why reinvent the wheel, use GSON - A Java library that can be used to convert Java Objects into their JSON representation and vice-versa
JSON-lib is a good library for JSON in Java.
String jsonString = "{message:'%message%',player:'%player%'}";
JSONObject obj = JSONObject.fromObject(jsonString);
System.out.println("<" + obj.get("message") + ">" + obj.get("player") );
You can also use xStream for doing it which has got a very simple API. Just Google for it.
You can always use the following libraries like:
- Jackson
- GSON
Ok here is the right way to do it Without using any library:
Eg:
JSONArray jarr = api.giveJsonArr();
// giveJsonArr() method is a custom method to give Json Array.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobj = jarr.getJSONObject(i); // Taking each Json Object
String mainText = new String(); // fields to hold extracted data
String provText = new String();
String couText = new String();
String fDatu = new String();
try {
mainText = jobj.getString("Overview"); // Getting the value of fields
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) {
}
try {
String cloText = jobj.getString("ClosingDate");
fDatu = giveMeDate(cloText);
System.out.println(fDatu);
} catch (Exception ex) {
}
}
As you see you have many alternatives. Here is a simple one from json.org where you find lots of other alternatives. The one they supply them selves is simple. Here is your example:
String json = "{\"result\":\"success\",\"source\":\"chat\",\"tag\":null,\"success\":{\"message\":\"%message%\",\"time\":%time%,\"player\":\"%player%\"}}";
JSONObject obj = new JSONObject(json);
JSONObject success = obj.getJSONObject("success");
System.out.println("<" + success.get("player") + "> "
+ success.get("message"));

Categories