Android application to web server with JSON lib - java

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

Related

Parse JSON having both Escape & Unescape characters in JAVA using Jayway

I receive the below json as an input to my program:
{
"shopping": {
"cart": {
"items": [{
"iturl" : "https://www.google.com/",
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
We are using jayway jsonpath to parse this data and do some processing and return the final value as a string.
when we parse it with the default jsonpath configuration, I get the iturl modified as "https:\/\/www.google.com\/"
Tried changing the JSONProvider to JacksonJsonProvider (by referring Jsonpath with Jackson or Gson) and the issue with the url is solved but, the value of itdesc is now coming to new line (due to \n) making it an invalid json.
I cannot specifically handle for each field as the incoming data will be dynamic.
Is there any proper way to parse this kind of JSON in java. Thanks in advance for your help
Try adding one more escaping level before parsing the string, the string parser's gonna give you "\n" for "\\n".
For example, parsing with Jackson ObjectMapper.
objectMapper.readValue(jsonString.replace("\\", "\\\\"), Any.class);
{
"shopping": { <-- JSONObject
"cart": { <-- JSONObject
"items": [{ <-- JSONArray
"iturl" : "https://www.google.com/", <-- JSONObject inside JSONAray
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
if this data json come from http connection.
this json must be a string format fisrt,
and try using org.json.simple
so do like this :
private void readData() {
String Body = (response json string from connection);
JSONParser parse = new JSONParser();
String iturl = null;
String itdesc = null;
try {
JSONObject shopping = (JSONObject) parse.parse(Body);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
}catch ( ParseException e) {
e.printStackTrace();
}
}
if this come from file.json combine with reader :
private static final File jsonData = new File(file.json);
private void callData() {
String iturl = null;
String itdesc = null;
try {
Reader reader = new FileReader(marketList);
JSONParser parse = new JSONParser();
JSONObject shopping = (JSONObject) parse.parse(reader);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}

Android - How to correctly write a JSONObject string

I'm trying to read/write a json file. But after the first write the json is escaped and reading it again doesn't work. I have the following json structure but with a lot more value :
{
"events": {
"XdQKixgtraz17eDHb6OW": {
"department": "Côte-d'Or",
"objectName": "Dijon",
"uid": "PMhzfzWlm6vN2yL1kY2i"
}
}
}
Here is how i build my json string :
JSONObject eventsJsonObject = new JSONObject();
JSONObject eventsData = new JSONObject();
for(Event event: eventsList){
String eventString = gson.toJson(event);
eventsData.put(event.getUid(), eventString);
}
eventsJsonObject.put("events", eventsData);
writeFile(filename, eventsJsonObject.toString());
I end up with a string looking like this and i can't read it again .. :
{"events":{"XdQKixgtraz17eDHb6OW":"{\"department\":\"Côte-d'Or\",\"objectName\":\"Dijon\",\"uid\":\"PMhzfzWlm6vN2yL1kY2i\"}"}}
As you can see there is a quote before the third semi colon that shouldn't be there. How can i correctly build my json string ?
Thanks for your time.
Edit : The error came from where i build my json string to write in file so i have rewrite my question.
Try this code
public static JSONObject readJSONFile (String path, Context context) {
String jsonStr = null;
try {
InputStream is = getActivity().getAssets().open(path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonStr = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
JSONObject jsonObj = new JSONObject((jsonStr ));
return jsonObj;
}

JSON stored as string. Cant seem to parse it - Java

This is what I have to read text in JSON format from a website. But i get the error
Java.lang.ClassCastException: org.json.simple.JSONObject cannot be
cast to org.json.simple.JSONArray
This is driving me nuts. Can anyone help? I also need to check this string for all instances of "Username" and run something for each of them.
public class CommandCheck implements CommandExecutor {
private String username;
private static String host = "example.com";
private URL url;
private String apiKey = main.getNode("API-KEY");
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg3) {
try {
this.url = new URL(CommandCheck.host);
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("x-api-key", this.apiKey);
}
conn.addRequestProperty("User-Agent", main.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
sender.sendMessage(response); //Im just dumping the raw String for the person running the command to see Debug mostly
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty()) {
sender.sendMessage("The Array appears to be empty");
return false;
}
JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
username = (String) latestUpdate.get("Username");
sender.sendMessage("whitelist add" + username);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
sender.sendMessage("I think there is an API key issue");
} else {
sender.sendMessage("Problem of unknown orign");
}
return false;
}
}
Try changing the following line:
final JSONArray array = (JSONArray) JSONValue.parse(response);
to:
final JSONObject jsObj = (JSONObject) JSONValue.parse(response);
Can you provide the JSON String you are trying to parse? I.e. the value of response?
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes") ;
org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray means that you are trying to convert the json object into the json array. if your response in the json object as a response then you first need it to convert in the Json object.
after converting you can get the the Json array from the json object using the get("key-name")
JSONObject resObj = new JSONObject(responseString);
JSONArray resArray = resObj.getJSONArray("Username");
for (int i=0; i<resArray.length(); i++)
String resultString = resArray.getString(i);
it gives you all usersname.
i think this code helps you to solve your problem.

getString not working for JSON key

I'm learning how to work with JSON's in java and I'm having a problem using getString for one of my keys. My code is here:
public static void getJSON(String matchID){
String s = "";
String test = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try {
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
String[] items = new String[stuff.length()];
items[0] = stuff.getString("firstName");
} catch (JSONException e) {
e.printStackTrace();
}
}
The "getString" is underlined in red, and the "The method getString(int) in the type JSONArray is not applicable for the arguments (String)" I was following an answer to another question word for word almost, and this happens, any advice? Thanks!
EDIT:
I need to get the specifics by name ie. "firstName" because I will be working with thousands of JSONs that each have hundreds of lines.
You need to get the JSOnObject first from the JSONArray(stuff) before you can call getString().
if you want to get the first element in the jsonarray and get its string this is how you would do it
JsonObject obj = stuff.getJsonObject(0);
String name = obj.getString("firstname");
So I figured out my problem, I didn't realize I had an JSONObject first, my apologies. Fixed like this:
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
JSONObject name = stuff.getJSONObject(0);
String[] items = new String[hi.length()];
items[0]=name.getString("firstName");
System.out.println(items[0]);
you can try the simplest way to Parse in JSON
JSONParser parser=new JSONParser();
String s = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(1));
}catch(ParseException pe){
}

How to get the data from the Json file in the following Code

I am new to json so please help me to get solve this
propertyAlerts: [
{
alertDomain: "oiq.core.alert.PropertyAlert",
alertType: "HERITAGE_DETECTED",
oiqCreatedDate: "2013-11-04 03:06:26"
}]
By using java, I want to get the following data
OUTPUT:
alertDomain: "oiq.core.alert.PropertyAlert"
alertType: "HERITAGE_DETECTED"
oiqCreatedDate: "2013-11-04 03:06:26"
The following is used by me
public void checklicense(String filename) throws Exception
{
JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./output_profiles/"+filename));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonMainArr = obj.getJSONArray("propertyalert");
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String alertDomain = childJSONObject.getString("alertDomain");
}
Can any one help me to solve this problem
This tutorial explains the basics of JSON parsing.
I would recommend you to read the entire post as it is something that you will do almost daily in Android development.
public static void checklicense(String filename)
{
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
System.out.println(obj.getClass());
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonMainArr = (JSONArray) jsonObject.get("propertyAlerts");
Iterator iterator = jsonMainArr.iterator();
while(iterator.hasNext()) {
jsonObject =(JSONObject) iterator.next();
String alertDomain = (String) jsonObject.get("alertDomain");
String alertType = (String) jsonObject.get("alertType");
System.out.println("alertDomain " + alertDomain + ", alertType " + alertType );
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(EosClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The above code produces the required output for a valid json input
{
"propertyAlerts": [
{
"alertDomain": "oiq.core.alert.PropertyAlert",
"alertType": "HERITAGE_DETECTED",
"oiqCreatedDate": "2013-11-04 03:06:26"
}
]
}

Categories