Convert JSONObject which contains \" to a normal string with JSON - java

I receive a string from an http request which contains data such as:
{"status":1,"Type":3,"Data":"<p style=\"padding-left:80px\"><\/p><ol><li><span style=\"color:#ff0000\">This<\/span><\/li><li>is a<\/li><li><strong>m<span style=\"background-color:#66cc00\">are<\/span><\/strong><\/li><\/ol><p><\/p><p style=\"padding-left:80px\"><strong style=\"text-align:left\"><span style=\"background-color:#66cc00\"><\/span><\/strong><\/p> "}
I convert it to a JSONObject like so:
jsonObj = new JSONObject(result);
I then need to get the html as a String to display in a TextView,
I have tried this:
String data = jsonObj.getString("data");
but data remains null. This works with simple json strings, but i think it might be cause of the " characters.

You are using "data" with a lowercase d, but your JSON contains "Data" with a capital D. Use this:
jsonObj.getString("Data");

You have used "data" instead of "Data". This is the only silly mistake you did. To avoid such type of typo mistake, always user final static String to access them from anywhere.
final static String KEY_DATA = "Data";
Then access it inside your class (suppose class name is Aclass):
jsonObj.getString(KEY_DATA);
And in other classes:
jsonObj.getString(Aclass.KEY_DATA);
This is a good practice indeed and no possibility of typo mistake!

Related

Is toString() mandatory while accessing the individual element of a JSON object in Java

I am quite new to Java and trying to understand the effect of using toString() while accessing the individual string elements of JSON object in Java.
Below are the steps followed:
Parse the JSON data. Let's assume only string elements are there in parsed JSON data.
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(json_data);
{
"firstname" : "new",
"lastname" : "human",
"id" : "some_id"
}
Try to access the individual elements.
Access without toString():
Public static String firstname = jsonObj.get("firstname");
Access with toString():
Public static String firstname = jsonObj.get("firstname").toString();
I do not see a difference when I try to print the data.
However I would like to know the difference between the above 2 methods, and also will there be any issues if I use without toString() in this particular case.
Appreciate your help.
Thank you
When you have some Int or other type of data type variables in your model class and you want to parse it into a string so for that we use toString(), it will convert int or any other data variable into a string, in your case here you already have string so no need to change again and again and JSON uses string variables when it comes from backend so that the purpose.
toString() returns string representation of property/object on which this method is called.
Whenever we print an object reference, it invokes the toString() method internally as a result , it is not making difference.
Because you are using Json, there is no difference.
You can use the Option, you like more

how to remove the slashes from json key while converting object into string

I'm trying to convert JSON object into string by doing the below
JSONObject object = new JSONObject();
object.put("video", data);
array1.add( object.toString().replace("\\\\"," "));
Actual result
["{\"photos\":\"/contests/1/images/1.png\"}",
{\"photos\":\"/contests/1/images/2.png\"}"]
Expected result
["{"photos":"/contests/1/images/1.png\"}","
{"photos":"/contests/1/images/2.png\"}"]
not able to remove the slashes from key
Use replaceAll instead of replace
replaceAll("\\\\", "")
When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.
Please use:
.replace("/\\/g","")
Alternatively, replaceAll can be used as #Code_Mono suggested
The Code_Mode mentioned is correct one.
Because String is immutable. Make sure that you put it right place.
You can refer code bellow for more detail:
public static void main(String[] args) {
String json = "[\"{\\\"photos\\\":\\\"/contests/1/images/1.png\\\"}\", {\\\"photos\\\":\\\"/contests/1/images/2.png\\\"}\"]";
json.replaceAll("\\\\","");
System.out.println(json);
String jsonReplace = json.replaceAll("\\\\","");
System.out.println(jsonReplace);
}
Output value:
["{\"photos\":\"/contests/1/images/1.png\"}", {\"photos\":\"/contests/1/images/2.png\"}"]
["{"photos":"/contests/1/images/1.png"}", {"photos":"/contests/1/images/2.png"}"]

how to correctly pick the json structure

Hi i have a php script that input user data into mysql and from mysql i get the results in an array and finally to json format by json_encode functino of PHP. The contents of the file are provided below.
[{"priority":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"}]
However now i need to get the json read in the JAVA and for ease i copy and paste the contents of the json file to string. I am able to read the contents but the positions has changed to the following sequence
here is the output
LENGTH IS____7
{"priority":"1","boolean":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
as you can see that the boolean has to be in the end but it pops up on the second number. i treid differenct codes from tutorials and did some my own as below but the result is same: help is needed in this matter.
jsonInput=[....as shown above the json contents....]
JSONArray ja = new JSONArray(jsonInput);
System.out.println("LENGTH IS____"+ja.length());
for(int x=0;x<ja.length();x++)
{
JSONObject jb = ja.getJSONObject(x);
System.out.println(jb);
}
System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
JSON doesn't specify an order for keys As Adrian Smith said :
JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
You probably use org.json. You can use the getString("myKey") to access the value in your JSONObject without knowing his position.
An other solution is to create a class that represents your data:
public class myClass{
private int priority;
private String rule_body;
private String cons;
private String boolean; //STRING ! 1 is not a valid boolean value.
}
Then create an ArrayList of your class and deserialize your JSON in it with Gson.
Gson myGsonTool = new Gson();
ArrayList<myClass> myData = gson.fromJson(myJsonString, ArrayList<myClass>.class);
Then, you have a POJO with all your data. You can access easily to your data now:
//If i want the value of rule body:
myData.get(0).getRule_Body();
I do not know the purpose of your program, so this is maybe not the best solution.
Edit: Gson maintains the order of records.

How to check json for key and if it exists then set the value in java model Object

I have a model object which is initialized with default values. To refresh the content of object I call an web service and get the response and get the content from json object.
I want to check If json response contains the object or not. If it does then call the setter and set the data and if it doesn't then leave then don't set it. I have approx 300 fields in my object. How I can do it with less code. I am listing my current approach.
My Model object is like
public class MyObject {
private String str1 = "Initial Value1";
private String str2 = "Initial Value2";
public void setStr1(String str1)
{
this.str1 = str1;
}
public void setStr2(String str2)
{
this.str2 = str2;
}
public String getStr1(){
return str1;
}
public String getStr2(){
return str2;
}
}
my json response be like
{
"val_one":"New Value1",
"val_two":"New_value2"
}
Now at run time I need to set the value from json response
MyObject myObject = new MyObject();
if(jsonObject.has("val_one"));
myObject.setStr1(jsonObject.get("val_one"));
if(jsonObject.has("val_two"));
myObject.setStr2(jsonObject.get("val_two"));
Now how to do it in a better and efficient
If both sides are using JAVA then why not just use json-io. You can create an object as normal. ie
Animal a = new Aminmal() andimal.setName("bob");
Then use json-io to make it into json -- stream to where ever it needs to be... use json io to change back to object
This can be done using
JsonWriter.objectToJson(Object o);
JsonReader.jsonToJava(String json);
https://code.google.com/p/json-io/
json-io is also extremely light weight and quicker than most if not all other third party json library's that I have used.
That being said if you want to have more control on the output ie.. date conversions etc.. then look at GSON.
https://code.google.com/p/google-gson/
Another option, in addition to the other suggestions is gson. Here the link for gson information.
Essentially the idea with gson being that you define an object to represent the JSON structure that you are receiving. So somewhat like what you have now, you'd just need to change the object attributes to match the names of the JSON fields, ie 'val_one' and 'val_two'.
Then you just need to use gson to create the object from the JSON text, eg:
Gson gson = new GsonBuilder().create();
MyObject json = gson.fromJson(jsonStr, MyObject.class);
Why do you want to take of the object model mapping yourself? If you take spring then you can use the jackson mapper and have it all done for you.
If you don't want to use spring then you still can use jackson2 and let it handle the parsing:
http://wiki.fasterxml.com/JacksonRelease20

String array calculation

i have a string array like
String[] resultYears = {"2013/07", "2013/08", "2013/09", "2013/10", "2013/11", "2013/12", "2014/01"};
when i get this through response in my jsp,
<% String[] resultYears = (String[]) request.getAttribute("resultYears");%>
i am getting the remainders of their respective values. How can i get same as above string value?
Try this way in your JAVA Class
String[] resultYears = {"'2013/07'", "'2013/08'", "'2013/09'", "'2013/10'", "'2013/11'", "'2013/12'", "'2014/01'"};
request.setAttribute("resultYears", resultYears);
Try the strings using single quotes like this
"'2013/08'"
How about instantiating a Date object with the YYYY/MM desired and do a .getTime() on it, then pass that through the request in String value. On the far end, translate it back into a pretty, human readable format.

Categories

Resources