Do you have to go through all lines in .json with gson? - java

I'm just starting off with json parsing and writing, and am using gson to do so.
Let's say I want to access something towards the bottom of the file, do you have to iterate through each line in the json file to get to that line?
How do you jump to Alice without having to iterate through everything Bob has? Right now I only know how to use beginObject(), beginArray() to open Bob, go through them, then close Bob, then reach Alice.
e.g.
{
"Bob": {
"following": [
215876567,
64044676,
276716878,
208675951,
151503222,
],
"followers": [
720567433,
1005407395,
2432297370,
2463742694,
2463741222,
51101660,
2463700218,
2463741192,
405107240,
]
},
"Alice": {
"location": "New York"
}
}

You can get direct Alice as below
JsonParserjsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(YOUR_JSON_STRING_HERE);
// get JsonElement for Alice as like this
JsonElement aliceJsonElement = jsonElement.getAsJsonObject().get("Alice");
It will give you this json object {"location":"New York"}
Finally you can parse it as
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(aliceJsonElement, mapType);
// iterate map
Like this you can get Bob AND following
jsonElement.getAsJsonObject().get("Bob")
jsonElement.getAsJsonObject().get("Bob").getAsJsonObject().get("following")

Related

How do I Convert JSON Array into ArrayList<ClassType> in Java?

This is my input JSON From which I have to fetch interLockingGrids and store it into ArrayList<ClassType>. I have searched enough already but didn't find exactly what I want. Is there is any simplest way?
{"entity":"MasterGrid",
"data" :"{\"name\":\"MA_Pune\",
\"coordinates\" : [
{\"lat\":18.553449789265677,\"lng\":73.77419574114515},{\"lat\":18.554232972087224,\"lng\":73.77367002817823},{\"lat\":18.556135000463573,\"lng\":73.77144913093571},{\"lat\":18.555148376025496,\"lng\":73.7700973257704},{\"lat\":18.55309341985624,\"lng\":73.77075145899971},{\"lat\":18.5530421437421,\"lng\":73.77312207276918} ] ,
\"interLockingGrids\": [
{\"name\":\"Test1\",\"type\":\"CLUSTER\",\"coordinates\":[{\"lat\":18.555151666563823,\"lng\":73.7700902617189},{\"lat\":18.556135000463573,\"lng\":73.77144913093571},{\"lat\":18.556135000463573,\"lng\":73.77144913093571},{\"lat\":18.556135000463573,\"lng\":73.77144913093571},{\"lat\":18.556135000463573,\"lng\":73.77144913093571},{\"lat\":18.556135000463573,\"lng\":73.77144913093571}],\"isActive\":true,\"colorCode\":\"#D0983C\"} ,
{\"name\":\"Test2\",\"type\":\"CLUSTER\",\"coordinates\":[{\"lat\":18.5530421437421,\"lng\":73.77312207276918},{\"lat\":18.553449789265677,\"lng\":73.77419574114515},{\"lat\":18.55238201763598,\"lng\":73.7743998478852}],\"isActive\":true,\"colorCode\":\"#8E75B7\"} ] ,
"operation":"GRID_OPERATION",
"description":"Baner_Test",
"submittedBy":"m#abc.com",
"submittedById":4,
"submittedByType":"OPS" }
In a recent project I did something similar:
public List<MyType> parseJsonToListOfMyType(String json) {
Gson gson = new Gson();
JsonArray job = gson.fromJson(json, JsonArray.class);
Type listType = new TypeToken<List<MyType>>(){}.getType();
return gson.fromJson(job, listType);
}

Using Gson to parse JSON with Objects but needing to exclude Arrays

I have a need to parse a JSON string containing Objects, but there can also be Arrays in the JSON, which I don't need, and it's currently crashing with:
com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
If I remove all the Arrays from the JSON, it works perfectly fine to parse the JSON with my POJO using the following code:
Type type = new TypeToken<Map<String, UsersPOJO>>(){}.getType();
Map<String, UsersPOJO> myUsers = gson.fromJson(JSONString, type);
But I'm having no luck parsing whenever there's Arrays in the JSON. I don't need, nor do I want to parse the Arrays, but if it's necessary, parsing the Arrays and then discarding the result would be okay.
How do I accomplish this with Gson? Or any other Java JSON library for that matter. Gson isn't a requirment.
This is an example of the JSON I'd be parsing:
{
"1002001":{
"level":2,
"name":"CaptKrunch",
"uid":1002001,
"user":{
"age":21,
"city":"None",
"country":"United States",
"creation":1269969663
},
"meta":{
"score":1762,
"rank":78
}
},
"1003001":{
"level":11,
"name":"LtRaine",
"uid":1003001,
"user":{
"age":35,
"city":"LA",
"country":"United States",
"creation":1269369663
},
"meta":{
"score":11562,
"rank":11
}
},
"tags_1002001": [
"conqurer",
"almighty"
]
}
You can skip array, if parse JSON string to JsonElement and iterate all elements:
Gson gson = new Gson();
//Type type = new TypeToken<Map<String, UsersPOJO>>(){}.getType();
//Map<String, UsersPOJO> myUsers = gson.fromJson(jsonString, type);
JsonParser parser = new JsonParser();
JsonElement topElement = parser.parse(jsonString);
Map<String, UsersPOJO> myUsers = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : topElement.getAsJsonObject().entrySet()) {
if (entry.getValue().isJsonArray()) {
//skip or process array
} else {
myUsers.put(entry.getKey(), gson.fromJson(entry.getValue(), UsersPOJO.class));
}
}

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...

How to parse this JSON with GSON?

I'am struggling with a problem to parse a JSON with GSON which contains lists as values. This should be pretty simple, but I can't figure out how to solve it. The JSON is:
{
"key1": [
"foo1",
"foo2",
"foo3"
],
"key2": [
"foo4",
"foo5",
"foo6"
],
"key3": [
"foo7",
"foo8",
"foo9"
]
}
I think the best way is to put it into a Map<String, List<String>>, but I can't create a Type for it. Like:
Type jsonArrayType = new TypeToken<Map<String, List<String>>>(){}.getType();
// Doesn't work, causes exception: "com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.List"
Thanks for any help!
You will get a java.lang.reflect.Type from the getType() method. Use that to parse your json. Here is a small working example (Java 7)
String json = "{\"key1\": [\"foo1\",\"foo2\",\"foo3\"],\"key2\": [\"foo4\",\"foo5\",\"foo6\"],\"key3\": [\"foo7\",\"foo8\",\"foo9\"]}";
java.lang.reflect.Type type = new TypeToken<Map<String, List<String>>>(){}.getType();
Map<String, List<String>> map = new Gson().fromJson(json, type);
System.out.println(map);
This snippet prints the below value
{key1=[foo1, foo2, foo3], key2=[foo4, foo5, foo6], key3=[foo7, foo8, foo9]}

Is there any tool to generate a String from a JSON?

My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.
So I want to know if thre is some tool to generate this String?
Some good choices are:
Jackson
Gson
They have built in methods to do just whatever you need to do in an efficient way...
I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.
You should use JSONObject and JSONArray to accomplish this.
To create this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
You should use this code:
JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");
JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");
JSONArray array = new JSONArray();
array.put(a);
array.put(b);
JSONObject root = new JSONObject();
root.put("my_json", array);
// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);
As told by Angel, Jackson and Gson are two cool libs.
Gson is very easy to use while Jackson has better performance.
Try here, Go through the answers mentioned below
How to convert String to JSONObject in Java
in short,
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Here put your own string.
Edit:
Try here,
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
Create a Json object,
JSONObject jsonobj = new JSONObject();
Put your data using...
josnobj.put()

Categories