How to parse entrie json file into map in Java with Gson? - java

I have different jsons and don't want to create classes for each.
Is there a way to parse entire json file into Map?
For example:
{
"response": [
{
"id": 1,
"first_name": "Pavel",
"last_name": "Durov",
"screen_name": "durov",
"photo_200_orig": "https://pp.vk.me/c625129/v625129631/34d5e/BkAwjDyPg.jpg"
}
]}
And do like this:
Map map = Gson.fromJson(jsonString, Someclass.class);
long id = map.get("response").get(0).get("id");
Is there a way?

Related

Jackson JSON Deserialization - How to assign object members based on JSON values?

I have some ugly JSON that I need to deserialize which looks like the following:
"ContainerValues": [
{
"ParentAttribute": "QuantityContained",
"RowList": [
{
"Values": [
{
"Name": "Code",
"ValuesByLocale": {
"en-US": "GRM"
},
},
{
"Name": "Value",
"ValuesByLocale": {
"en-US": "4.0"
},
}
],
}
],
}
],
This is just a sample of the JSON I have. All I need to do is to get this into a POJO which looks like something like the following:
Class POJO{
String grmValue; // This is the "Value" for the GRM "Code" above, i.e. "4.0"
...
}
Any idea how I might be able to assign the value of grmValue based on the JSON above using Jackson? I'm starting to think I'll need to write a custom deserializer.
First You have to deserialize to class similar to your JSON, then transform to your POJO format :)

Parse array in JSON using JsonPath in Java

I am using jayway JsonPath library to parse the JSON using the path given. I am able to get the string value if I give the correct path. But I want to get the list of maps when I give the path if its an array. For example, I have a JSON like below:
{
"employees": {
"company": "Google",
"people": [{
"name": "John",
"age": 25,
"location": "zurich"
},
{
"name": "Peter",
"age": 27,
"location": "Lucerene"
}]
}
}
Below is the code I am using to parse the json.
if I give the path $.employees.people, I am getting the String, But I need to List of Maps. Below is the code I am using to Parse Json using jsonpath.
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath) //But this is returning String
Anyone suggest proper approach to get what I expected.
try using,
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people[?]");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath);
if you need more details. readmore...

How to convert nested Json in string into Json object in java

I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar

How to get the JSON array values without have JSON object values in android? Is it Possible?

How to convert following type Json array in "tags_name": ["Activity Based"] in android and store data using getter setter methods.How to create POJO class, and how to handle when array is empty.I am struck with this concept.I tried this following way. Please guide me to resolve this issue.
API
"postlist": [
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [
"Activity Based"
],
"images_count": 0,
"images": [],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "992"
},
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [],
"images_count": 2,
"images": [
{
"gallery_id": "5549",
"name": "IMG_20161012_1832491.jpg",
},
{
"gallery_id": "5550",
"name": "IMG_20161012_1832441.jpg",
}
],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "993"
}
]
In Java i've use Following code.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
for(int iloop=0;i<tagNameArr.length();iloop++)
{
String street = tagNameArr.getString(iloop);
Log.i("..........",""+street);
}
} catch (Exception e) {
e.printStackTrace();
}
try this to get value of tags_name JSONArray.
ArrayList<String> temp = new ArrayList<String>();
JSONArray tagName= jsonResponse.getJSONArray("tags_name");
for(int j=0;j<tagName.length();j++){
temp.add(tagName.getString(j));
}
Use jsonschema2pojo.org service and Gson converter (lib from Google). select Gson converter on the site.
You can use gson
Gson gson = new GsonBuilder().serializeNulls().create();
RestaurantLoginResponseClass restaurantLoginResponse = gson.fromJson(loginResponseJsonString, RestaurantLoginResponseClass.class);
Add dependencies in app.gradle
compile 'com.google.code.gson:gson:2.6.2'
#MohanRaj , why you would to parse it ! , it is not clear , if you would to get the values and retain it in java object or save it in file system , you can use :
Gs
Gson gson = new Gson();
Staff obj = gson.fromJson(jsonInString, Staff.class);
if you have a list of object inside your json
you can create a list in your staff class something like :
#SerializedName("hits")
private List<Car> cars = new ArrayList<Car>();
GSON can understood it and parse the incoming list to those object .
you can get POJO from familiar JSON to java POJO tools :
http://www.jsonschema2pojo.org/
and you can check for more info https://sites.google.com/site/gson/gson-user-guide
http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html

parse Json to Map<String,String>

I have Json response like :
[
{
"first_name": "fname1",
"last_name": "lname1"
},
{
"first_name": "fname2",
"last_name": "lname2",
"city_name": "paris"
},
{
"first_name": "fname2",
"last_name": "lname2",
"city_name": "paris",
"Address": "1st Ave"
}
.
.
.
]
and my fields in JsonObject is dynamic so i can't use a class with predefined fields , so i've decided to use Map to parse the Json response as below :
Collection<List<Map<String,String>>> list_Objects = null;
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<List<Map<String,String>>>>(){}.getType();
list_objects = gson.fromJson(reader, collectionType);
but it throws me this error :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1
im not expert in Json parsing so please tell me where is my mistake or if there is another way to implement such behavior i would be very appreciated.
I think the problem is with your Collection wrapper on the List one.
You just need to define the list_Objects as List<Map<String, String>>.
I just tried the following with Jackson's ObjectMapper (which should work the same as GSON) and it worked ok:
List<Map<String, String>> list_objects = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, String>>>(){});
The result is a List of LinkedHashMap objects.
For your GSON example, you just need to remove the Collection<>, or the List<> if you prefer.
If I'm reading this correctly, you're defining your list twice.
Collection<List<Map<String, String>>> would map to a structure like
[ [ {"bla": "bla"}, {"bla": "bla"} ], [ {"foo": "bar"}, ... ], ... ]
(because List is a kind of Collection). So, try using List<Map<String, String>> and see if that works...

Categories