How to parse this kind of json String using Gson? - java

{
"status": "Success",
"message": "Contents retrieved successfully",
"name": {
"1": "God",
"2": "Goat"
},
"sites": {
"1": "google",
"2": "yahoo",
"3": "bing"
},
"places": [
"UK",
"AU",
"US"
],
"images": {
"1": {
"1x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png",
"2x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png"
},
"2": {
"1x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png",
"2x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png"
},
"3": {
"1x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png",
"2x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png"
}
}
}
My Class
import java.util.Map;
public class Data {
String status;
String message;
Map<String, String> name;
Map<String, String> Sites;
#Override
public String toString() {
return "Data [status=" + status + ", message=" + message
+ ", name=" + name + ", Sites=" + Sites
+ "]";
}
}
this class returns null value for the while retrieving sites and names

name and sites are JSONObjects no Arrays. Any Object in a JSON have to deserialised in a class using GSON.
So try this,
public class MyJson {
String status;
String message;
Sites sites;
List<String> places;
}
public class Sites {
String 1;
String 2;
String 3;
}
and so on for every Object. For Arrays you can use List / Map.
To use it make a call like this:
Gson gson = new Gson();
MyJson myJson = gson.fromJson(yourJsonString, MyJson.class);

JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse(yourString);
for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
JsonArray array = entry.getValue().getAsJsonArray();
for (JsonElement elementJSON : array) {
[...]
}
}

Related

JSON file processing with a different structure

I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}

How to parse the json object with multiple keys in android

I want to put the JSON result in textviews but because of multiple array i can get only one key/value of datetime, location and status objects. The json object is:
{
"signature":"testSignature",
"deliverydate":"2015-08-06 15:07:00",
"datetime":{
"0":1438848420,
"1":1438841820,
"2":1438838760,
},
"location":{
"0":"PA",
"1":"PA",
"2":"PA",
},
"status":{
"0":"packed",
"1":"On the go",
"2":"delivered",
},
"pickupdate":2015-08-04 07:55:00
}
and this is my java code:
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("NO", NUMBER_TO_POST));
JSONObject json = jsonParser.makeHttpRequest(URL_TO_POST, "POST", params);
success = json.getString(TAG_SIGNATURE);
if (success != null) {
SIGNATURE = json.getString(TAG_SIGNATURE);
DELIVERY_DATE = json.getString(TAG_DELIVERY_DATE);
JSONObject DT = json.getJSONObject(TAG_DATETIME);
DATETIME = DT.getString("0");
JSONObject LOC = json.getJSONObject(TAG_LOCATION);
LOCATION = LOC.getString("0");
JSONObject STAT = json.getJSONObject(TAG_STATUS);
STATUS = STAT.getString("0");
PICKUP_DATE = json.getString(TAG_PICKUP_DATE);
}else{
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
can anyone help me to solve this? Thanks
You should use GSON library to parse JSONs.
And to be a bit more helpful, here is how your class to hold JSON values might look like:
class MyClassForGsonToHoldParseJSON {
String signature;
String deliverydate;
Map<String, long> datetime;
Map<String, String> location;
Map<String, String> status;
String pickupdate;
}
Then just use something like this to conver variable json with JSON data to an object:
Gson gson = new Gson();
MyClassForGsonToHoldParseJSON f = gson.fromJson(json, MyClassForGsonToHoldParseJSON.class);
Your JSON format is wrong:
{
"signature": "testSignature",
"deliverydate": "2015-08-06 15:07:00",
"datetime": {
"0": 1438848420,
"1": 1438841820,
"2": 1438838760
},
"location": {
"0": "PA",
"1": "PA",
"2": "PA"
},
"status": {
"0": "packed",
"1": "On the go",
"2": "delivered"
},
"pickupdate": " 2015-08-04 07:55:00"
}

Output list of all paths to leaf nodes in a json document in java

For example: Given this json document:
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
I would like to produce (something like) this output:
store.book.category: "reference"
store.book.author: "Nigel Rees"
store.book.title: "Sayings of the Century"
store.book.price: 8.95
store.book.category: "fiction"
store.book.author: "Herman Melville"
store.book.title: "Moby Dick"
store.book.isbn: "0-553-21311-3"
store.book.price: 8.99
store.bicycle.color: "red"
store.bicycle.price: 19.95
expensive:10
Rather than work from raw text, I would prefer an efficient solution based on one of the robust json libraries (gson, jackson, etc.).
Here is a sample code with org.json. But the same can be used with Gson/Jackson with changes to appropriate types within those libraries. You could also using StringBuilder instead of String for the keys here.
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyJSONTest {
private static void listJson(JSONObject json) {
listJSONObject("", json);
}
private static void listObject(String parent, Object data) {
if (data instanceof JSONObject) {
listJSONObject(parent, (JSONObject)data);
} else if (data instanceof JSONArray) {
listJSONArray(parent, (JSONArray) data);
} else {
listPrimitive(parent, data);
}
}
private static void listJSONObject(String parent, JSONObject json) {
Iterator it = json.keys();
while (it.hasNext()) {
String key = (String)it.next();
Object child = json.get(key);
String childKey = parent.isEmpty() ? key : parent + "." + key;
listObject(childKey, child);
}
}
private static void listJSONArray(String parent, JSONArray json) {
for (int i = 0; i < json.length(); i++) {
Object data = json.get(i);
listObject(parent + "[" + i + "]", data);
}
}
private static void listPrimitive(String parent, Object obj) {
System.out.println(parent + ":" + obj);
}
public static void main(String[] args) {
String data = "{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"NigelRees\",\"title\":\"SayingsoftheCentury\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"HermanMelville\",\"title\":\"MobyDick\",\"isbn\":\"0-553-21311-3\",\"price\":8.99},],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},\"expensive\":10}";
JSONObject json = new JSONObject(data);
System.out.println(json.toString(2));
listJson(json);
}
}
Turns out this is pretty easy to do using Gson, especially with the JsonReader.getPath() method introduced in 2.3.
static void parseJson(String json) throws IOException {
JsonReader reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
while (true) {
JsonToken token = reader.peek();
switch (token) {
case BEGIN_ARRAY:
reader.beginArray();
break;
case END_ARRAY:
reader.endArray();
break;
case BEGIN_OBJECT:
reader.beginObject();
break;
case END_OBJECT:
reader.endObject();
break;
case NAME:
reader.nextName();
break;
case STRING:
String s = reader.nextString();
print(reader.getPath(), quote(s));
break;
case NUMBER:
String n = reader.nextString();
print(reader.getPath(), n);
break;
case BOOLEAN:
boolean b = reader.nextBoolean();
print(reader.getPath(), b);
break;
case NULL:
reader.nextNull();
break;
case END_DOCUMENT:
return;
}
}
}
static private void print(String path, Object value) {
path = path.substring(2);
path = PATTERN.matcher(path).replaceAll("");
System.out.println(path + ": " + value);
}
static private String quote(String s) {
return new StringBuilder()
.append('"')
.append(s)
.append('"')
.toString();
}
static final String REGEX = "\\[[0-9]+\\]";
static final Pattern PATTERN = Pattern.compile(REGEX);

Convert string to JSON array

I have the following string of a JSON from a web service and am trying to convert this to a JSONarray
{
"locations": [
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
}
]
}
I validated this String online, it seems to be correct. Now I am using the following code in android development to utilise
JSONArray jsonArray = new JSONArray(readlocationFeed);
This throws exception a type mismatch Exception.
Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}
Using json lib:-
String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);
Using GSON lib:-
Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);
you will need to convert given string to JSONObject instead of JSONArray because current String contain JsonObject as root element instead of JsonArray :
JSONObject jsonObject = new JSONObject(readlocationFeed);
String b = "[" + readlocationFeed + "]";
JSONArray jsonArray1 = new JSONArray(b);
jsonarray_length1 = jsonArray1.length();
for (int i = 0; i < jsonarray_length1; i++) {
}
or convert it in JSONOBJECT
JSONObject jsonobj = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsonobj.getJSONArray("locations");
Try this piece of code:
try {
Log.e("log_tag", "Error in convert String" + result.toString());
JSONObject json_data = new JSONObject(result);
String status = json_data.getString("Status");
{
String data = json_data.getString("locations");
JSONArray json_data1 = new JSONArray(data);
for (int i = 0; i < json_data1.length(); i++) {
json_data = json_data1.getJSONObject(i);
String lat = json_data.getString("lat");
String lng = json_data.getString("long");
}
}
}
if the response is like this
"GetDataResult": "[{\"UserID\":1,\"DeviceID\":\"d1254\",\"MobileNO\":\"056688\",\"Pak1\":true,\"pak2\":true,\"pak3\":false,\"pak4\":true,\"pak5\":true,\"pak6\":false,\"pak7\":false,\"pak8\":true,\"pak9\":false,\"pak10\":true,\"pak11\":false,\"pak12\":false}]"
you can parse like this
JSONObject jobj=new JSONObject(response);
String c = jobj.getString("GetDataResult");
JSONArray jArray = new JSONArray(c);
deviceId=jArray.getJSONObject(0).getString("DeviceID");
here the JsonArray size is 1.Otherwise you should use for loop for getting values.
It's a very simple way to convert:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getCredits() {
return credits;
}
public void setCredits(Integer credits) {
this.credits = credits;
}
public String getTwitter_username() {
return twitter_username;
}
public void setTwitter_username(String twitter_username) {
this.twitter_username = twitter_username;
}
#Override
public String toString() {
return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}
}
/*
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"hello#email.com","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"goodbye#email.com"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"mlsilva#email.com"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"fsouza#email.com"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can do the following:
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
If having following JSON from web service, Json Array as a response :
[3]
0: {
id: 2
name: "a561137"
password: "test"
firstName: "abhishek"
lastName: "ringsia"
organization: "bbb"
}-
1: {
id: 3
name: "a561023"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}-
2: {
id: 4
name: "a541234"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}
have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .
List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
User usr = mapper.readValue(jsonObj.toString(), User.class);
list.add(usr);
}
mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

How do I convert a JSON array into a Java List. I'm using svenson

I am trying to convert multiple objects of the same type into a List in Java. For example, my json would be:
{
"Example": [
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
{
"foo": "a3",
"bar": "b3",
"fubar": "c3"
}
]
}
I have a class:
public class Example {
private String foo;
private String bar;
private String fubar;
public Example(){};
public void setFoo(String f){
foo = f;
}
public void setBar(String b){
bar = b;
}
public void setFubar(String f){
fubar = f;
}
...
}
I want to be able to turn the json string I get into a list of Example objects. I would like to do something like this:
JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
List<Example> result = parser.parse(List.class, json);
Doing this I get an error:
Cannot set property Example on class java.util.ArrayList
You cannot convert this json to List but you can convert this to Map.
See your json String:
...
"Example": [
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
...
]
}
Here "Example" is key(String) and value is List object of Example.
Try this:
parser.addTypeHint("Example[]", Example.class);
Map<String,List<Example>> result1 = parser.parse(Map.class, json);
for (Entry<String, List<Example>> entry : result1.entrySet()) {
for (Example example : entry.getValue()) {
System.out.println("VALUE :->"+ example.getFoo());
}
}
Full code of Example:
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.svenson.JSONParser;
public class Test {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
String json = "{" + "\"Example\": [" + "{" + "\"foo\": \"a1\","
+ "\"bar\": \"b1\"," + "\"fubar\": \"c1\"" + "}," + "{"
+ "\"foo\": \"a2\"," + "\"bar\": \"b2\"," + "\"fubar\": \"c2\""
+ "}," + "{" + "\"foo\": \"a3\"," + "\"bar\": \"b3\","
+ "\"fubar\": \"c3\"" + "}" + "]" + "}\"";
parser.addTypeHint("Example[]", Example.class);
Map<String, List<Example>> result1 = parser.parse(Map.class, json);
for (Entry<String, List<Example>> entry : result1.entrySet()) {
for (Example example : entry.getValue()) {
System.out.println("VALUE :->" + example.getFoo());
}
}
}
}
public class Example {
private String foo;
private String bar;
private String fubar;
public Example(){}
public void setFoo(String foo) {
this.foo = foo;
}
public String getFoo() {
return foo;
}
public void setBar(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
public void setFubar(String fubar) {
this.fubar = fubar;
}
public String getFubar() {
return fubar;
}
}
OutPut:
VALUE :->a1
VALUE :->a2
VALUE :->a3
I solved it by modifying my JSON to be in the form:
[
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
{
"foo": "a3",
"bar": "b3",
"fubar": "c3"
}
]
Then I used the java code:
JSONParser parser = new JSONParser();
ArrayList list = parser.parse(ArrayList.class, json);
List<Example> result = new ArrayList<Example>();
for(int i = 0 ; i < list.size() ; i++){
HashMap<String, String> map = (HashMap) list.get(i);
Example example = new Example();
example.setFoo(map.get("foo"));
example.setBar(map.get("bar"));
example.setFubar(map.get("fubar"));
result.add(example);
}
i have a jsonstring like this :
[
{"author":"amahta","bookId":1,"bookName":"name"},
{"author":"amahta2","bookId":2,"bookName":"name2"}
]
and convert it to list by this snippet of code:
List<BookVO> listdata = new ArrayList<BookVO>();
JSONArray jArray = JSONArray.fromObject(booklist);
if (jArray != null) {
for (int i = 0; i < jArray.size(); i++) {
JSONObject obj = JSONObject.fromObject(jArray.get(i));
listdata.add(new BookVO(Long.valueOf(obj.get("bookId")), obj.get("bookName"), obj.get("author")));
}
}
i use net.sf.json-lib jar file.
String paymentMethod = "[{\"paymentType\":\"google_iap\",\"msisdn\":1486890084928,\"operator\":\"maroc_ma\",\"paymentMethod\":\"maroc_ma\",\"reactivationEnabled\":true }]";
PaymentMethod mop = null;
try {
mop = mapper.readValue(paymentMethod, PaymentMethod.class);
} catch (Exception e) {
logger.warn("Error while parsing paymentMethod = " + paymentMethod + " \n" + e);
}
List<PaymentMethod> result = new ArrayList<PaymentMethod>();
result.add(mop);
billingInfo.setPaymentMethods(result);

Categories

Resources