How to pull individual pieces of data from a JSON output String? - java

In Java, how would I pull the data for just the "data" section in the following JSON output?
{"getuserhashrate":{"data":1425,"runtime":8.2659721374512,"version":"1.0.0"}}
json.get("data") does not work and gives the following error:
Exception in thread "main" org.json.JSONException: JSONObject["data"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at so4308554.JsonReader.main(JsonReader.java:40)

You have a JSON object. It contains exactly one field: getuserhashrate
{"getuserhashrate": ... }
That field contains another JSON object which has its own fields ("data", "runtime", etc).
{"data":1425,"runtime":8.2659721374512, .. }
From looking at your stack trace, you're using the basic json.org library (or the Android SDK).
You'd parse the JSON and get back the top-level object via:
JSONObject root = new JSONObject(myJsonString);
Then you'd get the object contained in the getuserhashrate field:
JSONObject data = root.getJSONObject("getuserhashrate");
Now you are able to access the fields of that object.

JsonPath is a good tool to extract information from JSON
{"getuserhashrate":{"data":1425,"runtime":8.2659721374512,"version":"1.0.0"}}
String json = yourStringjson;
String data = JsonPath.read(json, "$.getuserhashrate.data");
data will be 1425
Just add the libs and it will be a useful tool if you dont want to create beans to have a full marshall
https://code.google.com/p/json-path/

Related

Interpolate JSON values into a string

I am writing an application/class that will take in a template text file and a JSON value and return interpolated text back to the caller.
The format of the input template text file needs to be determined. For example: my name is ${fullName}
Example of the JSON:
{"fullName": "Elon Musk"}
Expected output:
"my name is Elon Musk"
I am looking for a widely used library/formats that can accomplish this.
What format should the template text file be?
What library would support the template text file format defined above and accept JSON values?
Its easy to build my own parser but there are many edge cases that needs to be taken care of and I do not want to reinvent the wheel.
For example, if we have a slightly complex JSON object with lists, nested values etc. then I will have to think about those as well and implement it.
I have always used org.json library. Found at http://www.json.org/.
It makes it really easy to go through JSON Objects.
For example if you want to make a new object:
JSONObject person = new JSONObject();
person.put("fullName", "Elon Musk");
person.put("phoneNumber", 3811111111);
The JSON Object would look like:
{
"fullName": "Elon Musk",
"phoneNumber": 3811111111
}
It's similar to retrieving from the Object
String name = person.getString("fullName");
You can read out the file with BufferedReader and parse it as you wish.
Hopefully I helped out. :)
This is how we do it.
Map inputMap = ["fullName": "Elon Musk"]
String finalText = StrSubstitutor.replace("my name is \${fullName}", inputMap)
You can try this:
https://github.com/alibaba/fastjson
Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

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

Reading from big json data in java

To start off, I'm pretty new in programming. I have to create an Android Weather App for a school project and I'm stuck with this big ass JSON:
JSON Data
Out of this, how would I read the temperature out of every 3 hour interval(example: 9.00-12.00 temperature: 5°C, 12.00-15.00 temperature: 7°C etc.).
So I have an Activity that displays the temperature of the entire day by three hour intervals. Since I have no experience with JSON I have no idea what the certain indexes mean, when does it increment(there are like 8 main: thingies).
DISCLAIMER: I have to use JSON, no GSON or other shortcuts, I have to parse and read certain data from this JSON. I get this JSON from open weather map API so it changes every day.
API
Use volly library for it. You can easily fetch data from json. No async task is needed, if you are using volly library.
First validate the json by going to http://jsonlint.com/. This will help you see the formatted Json string.
Next read up on Json array and Object .
Use AsynTask to get the Json into forecastJsonStr string.
Then you need to convert this forecastJsonStr into JSon object forecastJsonObj
To get weather data in "list" do something similar to
JSONArray weatherArray = forecastJson.getJSONArray("list");
Hope this helps
JSONObject receivedData = new JSONObject("The string that you get as response from the API");
JSONArray weatherList = receivedData.getJSONArray("list");
for(int i=0;i<weatherList.length();i++){
JSONObject data = weatherList.getJSONObjectAt(i);
String date_text - data.getString("dt_txt");
JSONArray weatherData = weatherList.getJSONArray("main");
for(int j=0;j<weatherData.length();j++){
// Here is where you will get all the weather stuff that you need
int temp = weatherData.getInt("temp");
// Similarly other values like temp_min, temp_max
}
}
So basically you need to parse the entire thing. In order to understand the whole structure more clearly use something like http://jsonviewer.stack.hu/ in order to view the JSON in a more clear way so that you know what you need from the JSON data better. Simple copy paste your data into there and click "Format".
JSON is just a name-value pair kind of storage if you see stored like "name":"value". Integer values don't have the "".
Remember all the JSON is stored in { } and a JSON can be nested in a JSON. So in your example if you see, the entire thing is a JSON. Within that you have a "city" key which has a value within { }. So "city" is a JSONObject.
Similarly "coord" is a JSONObject while "cod" is a String and "cnt" is an integer.
There can also be some instances where a name points to an array of JSON objects like "list" over here. JSON Arrays are signified using a [ ]. Enclosed within are JSON objects separated by comma.
Above is a very simple sample to get you started so that you get a jist of what is going on. So play around and try to extract more data from in there.
All the best and Happy Coding :)

How to read twitter feed in json using jackson library

I am trying to create a jNODE object by parsing a JSON file which is in following format:
{"delete":{"status":{"id":222318827684372480,"user_id":372364809,"id_str":"222318827684372480","user_id_str":"372364809"}}}
{"delete":{"status":{"id":430870775227117568,"user_id":582666020,"id_str":"430870775227117568","user_id_str":"582666020"}}}
{"delete":{"status":{"id":217335495406010368,"user_id":418026096,"id_str":"217335495406010368","user_id_str":"418026096"}}}
While creating jNODE object I am getting an object corresponding to:
{"delete":{"status":{"id":222318827684372480,"user_id":372364809,"id_str":"222318827684372480","user_id_str":"372364809"}}}
and not rest of the two blocks in the JSON file. Can anyone please help with this?
We have tried to use an iterator to travel but it didnt work. Thanks.
Try enclosing the twitter feed in an array and it might be able to parse multiple lines :
[
{"delete":{"status":{"id":222318827684372480,"user_id":372364809,"id_str":"222318827684372480","user_id_str":"372364809"}}}
,
{"delete":{"status":{"id":222318827684372480,"user_id":372364809,"id_str":"222318827684372480","user_id_str":"372364809"}}}
,
{"delete":{"status":{"id":222318827684372480,"user_id":372364809,"id_str":"222318827684372480","user_id_str":"372364809"}}}
]

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