I have some code not shown here that pulls an IMEI number in JSON format from a database via a WCF and I now have it in the following format which I can display,
{"getIMEIResult":"268003456767887"}
Via,
jsonResponse = new JSONObject(new String(buffer));
IMEICheckResponse = jsonResponse.toString();
And then Toast IMEICheckResponse to get
{"getIMEIResult":"268003456767887"}.
How do I extract 268003456767887 from the JSON object and put it into the IMEICheckResponse string?
Cheers,
Mike.
Its very simple,
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
Log.d("output", IMEICheckResponse);
Related
I'm trying to create a JSON Object from a String. The String looks like this: {"case":"getAllProducts"}.
Why is jobj always empty?
String received = textMessage.getText();
System.out.println(received); //{"case":"getAllProducts"} - perfect
JsonObject jobj = new Gson().fromJson(received, JsonObject.class);
System.out.println(jobj); //{} - why empty???
String reqCase = jobj.get("case").getAsString();
I already checked out other articles here where its done exactly like I did. I can't find my problem here..
Instead of
new Gson().fromJson(received, JsonObject.class);
it should be
new Gson().fromJson(received, YourClass.class);
where YourClass is a user defined class having attributes same as the attributes in your JSON.
This question already has answers here:
How to parse json parsing Using GSON in android
(5 answers)
Closed 2 years ago.
Context: I'm having trouble getting a value out of a JSON returned by OpenWeatherMap's API via Android.
My JSON looks like this:
{"coord":{"lon":-78.32,"lat":38.55},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":269.05,"feels_like":265.34,"temp_min":267.59,"temp_max":270.37,"pressure":1010,"humidity":78},"visibility":10000,"wind":{"speed":1.25,"deg":293},"clouds":{"all":25},"dt":1607493640,"sys":{"type":3,"id":2006561,"country":"US","sunrise":1607516385,"sunset":1607550737},"timezone":-18000,"id":4744896,"name":"Ashbys Corner","cod":200}
It is stored in a JsonObject (Part of GSON, not to be confused with JSONObject) from a URL like so:
URLConnection requestWeather = weatherUrl.openConnection();
requestWeather.connect(); // connect to the recently opened connection to the OpenWeatherMaps URL
JsonElement parsedJSON = JsonParser.parseReader(new InputStreamReader((InputStream) requestWeather.getContent())); //Convert the input stream of the URL into JSON
JsonObject fetchedJSON = parsedJSON.getAsJsonObject(); // Store the result of the parsed json locally as a json object
Problem: I want to get the value associated with "main" out of the JSON (which in this case should be "Clouds").
Attempted Solution: I've attempted to get the value of main out like this:
String weatherType = fetchedJSON.get("weather").getAsString();
but this throws a java.lang.UnsupportedOperationException: JsonObject exception.
Question: How do I get the value of "main"?
You can use JACKSON or GSON library for fast parsing of Json data using model class.
JACKSON and GSON are dedicated to processing (serializing/deserializing) JSON data.
Raw Parsing via GSON
JsonObject fetchedJSON = parsedJSON.getAsJsonObject();
//weather is an array so get it as array not as string
JsonArray jarray = fetchedJSON.getAsJsonArray("weather");
// OR you use loop if you want all main data
jobject = jarray.get(0).getAsJsonObject();
String main= jobject.get("main").getAsString();
Although if you want raw parsing then you can do like ::
JSONObject obj = new JSONObject(yourString);
JSONArray weather = obj.getJSONArray("weather");
for (int i = 0; i < arr.length(); i++)
{
String main= arr.getJSONObject(i).getString("main");
......
}
When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
Below is my JSON String. I am trying to extract hosts from it.
{"description":"DescA","process_running":"sf","hosts":{"dc1":["machineA","machineB"]}}
Since hosts is a JSON String in itself and I would like to extract that JSON String from it. I am using GSON here -
String ss = new String(bytes, Charset.forName("UTF-8"));
// here ss is the above JSON String
Map<String, Object> data = gson.fromJson(ss, Map.class); // parse
I was trying to use Map to deserialize but the result it coming like this in the data-
{description=DescA, process_running=sf, hosts={dc1=[machineA, machineB]}}
Is there any way, I can extract hosts in the JSON format?
The easiest way I can think of to do this would be to use gson to create a tree of json elements from your map, and ask it to give you just the hosts node:
Map<String, Object> data = gson.fromJson(ss, Map.class); // parse
JsonObject jsonTree = (JsonObject) gson.toJsonTree(data);
String hostsJson = jsonTree.get("hosts").toString();
Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.