Problem:
I am unable to parse json request to an object containing double quotes in it.
For example:
jsonString = {
"desc":"Hello stackOverFlow, please reach on this email "asdas#gmail.com". thanks";
}
When I am trying to convert this I am not able parse to an variable, because it looks like invalid json but in real time the request has double quotes in it.
Please show me some good parsing techniques which can do parse this type of requests.
Thanks
You have to escape all of the double quotes, so for example:
String json = "\"{\"desc\":\"Hello stackOverFlow, please reach on this email \"asdas#gmail.com\". thanks\"}";
As you can see it is a lot of work to create very simple JSON, so you are better of using some library for that. I recommend you org.json, it is very lightweight and easy to use. Using it, it would look like this:
JSONObject json = new JSONObject();
json.put("description", "Your description....");
String jsonString = json.toString();
Related
I'm in the process of converting my website to an Android app and one of the pages' data currently is populated via JSON in my website. The way it works is that the URL generates a different JSON data with the same structure based on the passed ID. I already have the logic for passing the ID to the URL. Now I want to read the data through Java code and parse the JSON children and its values in it.
I have a URL that leads to the JSON file in textual form, but I'm not sure how to go about reading the data from it and accessing the child nodes based on the JSON key.
So I guess what I'm asking is what is the usual approach for this procedure? I see a lot of different examples, but none of which are applicable to my problem.
Anyone have any suggestions as to how I should approach this?
JSONObject = new JSONObject(yourjsonstring);
Now you have your Json Object...
If your Json start with array use this:
JSONArray = new JSONArray(yourjsonarray);
You can use existing libraries to parse JSON, gson or Moshi are two solutions.
The way you go about parsing the JSON is as followed
First you need to make pojo's with the same structure as the JSON file.
then you can parse it to java code via the fromJSON() method, this will make new objects and fill it with the data from the JSON.
gson example for clarification:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
where jsonLine = your json file and the Response.Class the pojo in which you want to json to load.
Now you have the JSON values as Java classes in response.
If you're using Retrofit and OkHTTP to perform the network calls i suggest you use Moshi as it's also from Square and claimed to work faster and better than gson. (if you want to know why you can leave a comment).
I think what you're trying to do is this
on post execute method do the following
#Override
protected void onPostExecute(String result) {
String status = "";
String message = "";
String tag = "";
String mail = "";
try {
JSONObject jsonResult = new JSONObject(result);
status = jsonResult.optString("status");
message = jsonResult.optString("message");
tag = jsonResult.optString("tag");
mail = jsonResult.optString("mail");
} catch (JSONException e) {
e.printStackTrace();
}
of course your json array contains different keys
Just reolace them with yours
I want to get the value of String and I am trying to put the string in the JSON and get it. The format of string is "key=value&key1=value". The code I am using is:
JSONObject json = new JSONObject(String);
String value = json.get("key").toString();
That string is url encoded not json formatted.
You can use a url decoder instead. Something like http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html might work for you.
I used Patterns and Matchers and it worked perfectly. Thank you.
I am developing a web-app using AJAX requests on the client-side and Servlets on the server-side.
My aim is to send objects of Javascript to server, then do some manipulations there and send it back to show here.
Let's say my js object is
var obj={hero:"Spiderman",name:"Peter Parker"};
My Approach
1.Convert obj to JSON string and send
var str= JSON.stringify(obj);
xmlhttp.open("POST",myurl,true);
xmlhttp.setRequestHeader("Content-Type","application/json",true);
xmlhttp.send("data="+str);
2. Recieve string,convert this back to JSON, manipulate "name" to "Bruce Wayne" and send it back as string
3.Recieve and convert back to Json
var data= JSON.parse(xmlhttp.responseText);
I am struggling at second point.I am using org.json for it .I searched and read docs but could not find satisfied answer for converting string to json and vica-versa in JAVA in my context.
It would be really helpful one could provide simple working code or point to some links where I can study.
P.S :
I cannot use Jquery as I am using AngularJS. See Why?
I will always send valid JSON string.
I can use other JSON lib. if its good than org.json and satisfy my needs.
Please provide its jar download link.
Assuming you are able to pull out data in your server code
This is how you can do it using org.json:
JSONParser parser = new JSONParser();
JSONObject requestObj = (JSONObject) parser.parse(data);
String name = (string)requestObj.get("name");
name = "Bruce Wayne";
Code to create the response can look something like this:
JSONObject response = new JSONObject();
response.put("name",name);
return response.toJSONString();
This assumes your server method returns a String type
And in case if you are using Servlet you can use HttpServletResponse object res to create response like:
res.setContentType("application/json");
OutputStream os = res.getOutputStream();
os.write(response.toString().getBytes());
os.close();
I'm relatively new to using JSON and all I really need to do read in a few key value pairs from a JSON file on the file system.
What I figured I would do is read in the file as a string and then parse it that way but it seems kind of redundant that way.
Here's what my file will be like:
{
"username" : "myname"
"domain" : "mydomain"
}
So essentially I need some help making an easy and efficient block of code to read in the key/value pairs. I've been trying to use GSON for the most part and haven't had much luck with examples I've found.
Thanks everyone
One other alternative is JSON.org, in which creating a JSON object from a JSON string requires only one line:
JSONObject jsonObject = new JSONObject(someJSONString);
When you need to access its value, use the functions that the JSONObject provides. For example,
String userName = jsonObject.getString("username");
String domainName = jsonObject.getString("mydomain");
I am having a really challenging time parsing some XML data returned to my Android app.
The data is sent as XML but printing it on my mobile screen, it comes out as the following:
{"sessid":"5eed0b52c6953b52e262b559b5557be4","session_name":"SESS6cbf091341a26e4687fa7850b465755a,"user":{"uid":"15","name":"guest","pass":"084e0343a0486ff05530df6c705c8bb4","mail":"adeoduye#hotmail.com", "mode":"0","sort":"0","threshold":"0","theme":"","signature":"","signature_format":"0","created":"1306008217","access":"1306094503","login":"1306134979","status":"1","timezone":"3600","language":"","picture":"","init":"adeoduye#hotmail.com","data":a:1:{s:13:\"form_build_id\";s:37:\"form-49ea7a4ef10a8a2b31478696f17e8dee\";","form_build_id":"form-49ea7a4ef10a8a2b31478696f17e8dee","roles":{"2":"authenticated user","3":"guest"}}}
Can anyone please help a newbie and give me some ideas on how to parse this type of output and/or plain XML?
This isn't XML but JSON. You have to parse that string using the JSON API.
Basically you create a JSONObject by feeding the string into a JSONTokenizer. You can now query the values from the JSONObject as described in the API reference example.
The String you're seeing here is in JSON format. You can parse this in Andriod using the following library : http://code.google.com/p/google-gson/
For more info on json, checkout http://json.org.