im trying to convert data from json array to json object but I'm getting an error and I don't know why
java code here
void addToList(String json)
{
try
{
ja = new JSONArray(json);
for(int i = 0;i<ja.length();i++)
{
JSONObject item = ja.getJSONObject(i);
String sent = item.getString("#")+" x "+item.getString("name");
items.add(sent);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
itemlist.setAdapter(adapter);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
json = ["{"name":"fish","#":"1"}"]
and the error I'm getting is
org.json.JSONException: Value {"name":"fish","#":"1"} at 0 of type java.lang.String cannot be converted to JSONObject
This is the constructor of a JSONObject:
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
That means in your case specifically that json can't be an array. Try using something like:
json = "{"name":"fish","#":"1"}"
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.
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;
I have JSON which I get from server:
"[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"},
{\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]"
I am using that json and sending to my thread (android thread):
try {
// Method from which I am getting Json described above
String s = dm.getAllUsers();
/*JSONParser jp = new JSONParser();
JsonElement jelement = new JsonParser().parse(s);
JsonArray array1 = jelement.getAsJsonArray();*/
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject menuObject = array.getJSONObject(i);
// doing something with the object
}
} catch (JSONException e) {
e.printStackTrace();
}
I can not process that Json at all.
I am getting the error "java.lang.String cannot be converted to JSONArray".
A know that problem is caused by "\", and I just do not know how to get rid of "\".
I tried:
1) s.replace("\\", "");
2) s.replace("\"", "'");
3) s.replaceAll("\\", "");
4) s.replaceAll("\"", "'");
In order to erase "\" but replace do not react at all.
I also tried to solve problem with "google-gson-2.2.2" library (code under the comment above, under the method).
Any advice, please?
Try this solution.
s.replaceAll("\\\\", "");
This will definitely work.
Problem has been solved with:
1) s = s.trim();
2) s = s.substring(1, s.length()-1);
3) s = s.replace("\\", "");
My json has been retrieved with "double quotes" on the beginning and on the end. I do not know how string variable can not figure out that "double quotes" is for "beginning" and for "ending" of string.
Thank you everybody for helping.
It is working for me...
In your json the value of "Your Json" is inclused inside "" so it's considered a string not an array..
So the solution is one of two things:
If you can modify the server response, remove the "" from arround the json array. or parse it first as string and then create a json array from that string like..
String notes = jobj.getString("GetNotesResult");
jarray = new JSONArray(notes);
I have no idea why its not working for you. Dot net web services do respond with \ but Java capable of parsing it. I did as below and it worked.
I've coded like this.
JSONArray users = null;
String jsStr = "[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"}, {\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]";
try {
users = new JSONArray(jsStr);
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("JSONStr", String.valueOf(users.length()));
for(int i = 0; i<users.length(); i++){
try {
Log.v("Name", users.getJSONObject(i).getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
See the LogCat
03-18 16:34:46.459: V/JSONStr(307): 4
03-18 16:34:46.479: V/Name(307): Milos
03-18 16:34:46.479: V/Name(307): Boban
03-18 16:34:46.479: V/Name(307): Pele
03-18 16:34:46.479: V/Name(307): admin
Your json will be valid only if you remove the back slashes () in between. You could use something like:
strJson = strJson.replaceAll("\\\\", ""); OR strJson = strJson.replace("\\", ""); to remove the slashes () in between your json String. Please note that replaceAll() method treats the first argument as a regex, so you must double escape the backslash but, the replace() method treats it as a literal string, so you only have to escape it once. Please have a look at the below example for better understanding: I have kept your json text in a file named json.txt in my hard-drive for demonstration. The contents in the file looks like this:
[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"},
{\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]
Now the code for getting the json array:
package com.stackoverflow.com;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("C:/Users/sarath_sivan/Desktop/json.txt");
BufferedReader br = new BufferedReader(fileReader);
StringBuilder strJsonBuilder = new StringBuilder();
String strLine;
while((strLine = br.readLine()) != null) {
strJsonBuilder.append(strLine);
}
String strJson = strJsonBuilder.toString();
strJson = strJson.replaceAll("\\\\", ""); /*OR you can use strJson = strJson.replace("\\", "");*/
JSONArray jsonArray = new JSONArray(strJson);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject menuObject = jsonArray.getJSONObject(i);
System.out.println("id: " + menuObject.getInt("id"));
System.out.println("name: " + menuObject.getString("name"));
System.out.println("city: " + menuObject.getString("city"));
System.out.println("email: " + menuObject.getString("email"));
System.out.println("password: " + menuObject.getString("password"));
System.out.println();
// do something with your JSON
}
fileReader.close();
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
s = s.replace("\\", "");
System.out.println(s);
You need to assign your modified String back to s. This gives a proper parsable JSON.
I don't really like the various String.replaceAll(rexex, "") solutions. What if some of the strings in your JSON contain a \ as part of the information rather than the formatting? I see a 'password' field in your JSON. I don't know whether this is going to be clear text or a hash, but in the case of the former, your program might break if a user uses a backslash in their password.
What you want to do here is unescape a string. This is a problem that as far as I can tell, can't be solved with a simple regex, but it is a problem that has been solved thousands of times before. No need to reinvent the wheel.
How to unescape a string literal in java
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"));