JSON String to JSON in Java - java

I have a couple of txt files that gets some information from android's (call,messages,etc) database and stores it as a Cursor object.
I then convert the Cursor onto a JSON object which is then stored on a txt file on an SD card on the device. When I read from the file I get lines as a String like this one:
{"date":1332969098495,"duration":0,"number":"7038673588","Device_ID":"streak"}
I have to store the values of the String onto a MySQL table. Is there a way that I can convert this back onto a JSON or maybe a Map?
I thought about editing the String so the values are surrounded by a single quote and use the MySQL syntax to simply load the fields on the file.
Thanks!

You can create a JSONObject from the string that you have. That will pretty much give the same functionality as that of java.util.Map. For e.g,
String jsonStr = "json representation of your data";
JSONObject jObj = new JSONObject(jsonStr);
jObj.get(yourKeyString);
//do more with your jObj here...
Hope this helps. Refer the JSONObject documentation for more details.

You need to use JSon-lib (or) GSon libraries for this purpose.
Example GSon code would be:
YourObject obj = gson.fromJson(inputJson, YourObject.class);
Note: YourObject is java class with getter/setter.

Here is an tutorial of using GSON library to achieve typed object conversion.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/

Sathishpaul is correct but just to clarify :
JSONObject obj = new JSONObject(YourJSONString);
Long date = obj.getLong("date");
int duration = obj.getInt("duration");
etc..

Related

Android - Accessing JSON children from a URL

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

Simplest way to read from a JSON file in Java?

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");

Java object from JSON input file

Hi I have a json input file as follows,
{'Latitude':'20',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
How to create a java object from the json input file.
Thanks
You can use the very simple GSON library, with the Gson#fromJson() method.
Here's an example: Converting JSON to Java
There are more than one APIs that can be used. The simplest one is JSONObject
Just do the following:
JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....
there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.
You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

Java Json / Gson put json encoded string to jsonObject without string escapes

i first create a Json String with
String myJsonString = new Gson().toJson(myElement);
this works fine.
After that, i want to add this String to anothe big jsonObject to send it to backend with other vars.
jsonObject.put("Tests",myJsonString);
but with this line of code the special character will be escaped and the parser on the backend didnt get it.
How can I avoid it, that myJsonString will be serialized again?
jsonObject.put("Tests",myElement);
doesnt work, because after that there are only references in the jsonObject but no values.
jsonObject.put("Tests", new JSONObject(myJsonString));
(assuming jsonObject is of type org.json.JSONObject)

org.json.JSONObject constructor not accepting what appears to be a valid JSON string

I have a string in an Android app that I am trying to convert into a JSONObject. The string looks like this (except longer and with actual values instead of the dummy values I entered here):
[[{"1":"a"}],[{"1a":"1a","1b":"1b"},{"2a":"2a","2b":"2b"}]]
I have entered this exact string into two online JSON validators, and both of them confirm it to be valid JSON data. So I would assume that the JSONObject constructor would be able to accept this string and convert it into a JSONObject. But when I try:
json = new JSONObject(result);
Where "result" is a String variable containing the string listed above, I get the following exception:
JSONException: A JSONObject text must begin with '{' at character 1 of [[{"1":"a"}],[{"1a":"1a","1b":"1b"},{"2a":"2a","2b":"2b"}]]
What's going on here? Is the JSONObject's parser broken?
You are trying to create a JSONObject, but what you are actually giving it is a JSONArray. Did you try creating a JSONArray instead?
Alternatively, you could wrap your array in an object so that you can create a JSONObject out of it.
I would suggest using the GSon library instead as it appears to be more full-featured.
In addition, it may be helpful to use this tool to test your data (your data is valid btw):

Categories

Resources