this is file1.json
[
{
"name": "Leonard",
"age": 28,
"city": "Pasadena"
},
{
"name": "joey",
"age": 29,
"city": "NewYork"
}]
this is file2.json
[
{
"name": "Shelly",
"age": 28,
"city": "LA"
},
{
"name": "Chandler",
"age": 29,
"city": "NewYork"
}]
So, how to merge these 'file1.json' and 'file2.json' into a single file by using the google GSON library in java?
List.addAll() may solve the problem, partially. If the same object appears in both JSON files, you may end up with duplicated objects in the result. Say you want each object in the array to be considered "distinct" by a specific key (e.g.: "name"). Then you should take a look at jsonmerge.
I'm assuming that the output you require is a new file with a single array of objects.
Following is the code required to achieve that :
Gson gson = new Gson();
JsonReader reader1 = new JsonReader(new FileReader(new File(/path of "file1.json"/)));
List<String> data1 = gson.fromJson(reader1 , List.class);
JsonReader reader2 = new JsonReader(new FileReader(new File(/path of "file2.json"/)));
List<String> data2 = gson.fromJson(reader2, List.class);
data1.addAll(data2);
FileWriter fileWriter = new FileWriter(/path of the output file/);
gson.toJson(data1 , fileWriter);
fileWriter.flush();
fileWriter.close();
JsonReader reads a JSON encoded value as a stream of tokens. The tokens are traversed in depth-first order, the same order that they appear in the JSON document.
fromJson reads the JSON value from the reader and converts it to the type given in the second argument i.e., java.util.List
After we get the list from both the JSON files, we merge them by using addAll method of java.util.List package.
We take the merged list and use toJson to serialize the specified list into its equivalent JSON representation.
The JSON in the new file is as follows :
[{"name":"Leonard","age":28.0,"city":"Pasadena"},{"name":"joey","age":29.0,"city":"NewYork"},{"name":"Shelly","age":28.0,"city":"LA"},{"name":"Chandler","age":29.0,"city":"NewYork"}]
Related
i'm having a problem with GSON, i'm trying to get a json file and transform them into a list of objects, i have no idea how to solve that, i tried to follow the article below but im recieving this error message below.
article: https://attacomsian.com/blog/gson-read-json-file
test.json
[
{
"code": "sasdsa321",
"items": [
{
"id":"1",
"name":"item1"
},
{
"id":"2",
"name":"item2"
},
...
]
},
...
]
my code
Gson gson = new Gson();
// create a reader
Reader reader = Files.newBufferedReader(Paths.get("test.json"));
// convert JSON array to list of items
List<Item> items= new Gson().fromJson(reader, new TypeToken<List<Item>>() {}.getType());
// print users
items.forEach(System.out::println);
Error message
"com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1 path $"
I want to use arraylist instead of vector since ArrayList gives better performance etc. However the code works using vector as well. I dont understand when i use json_encode, sometimes it can be parsed in arraylist and sometimes in vector. What makes difference on casting the json parsed value to vector and arraylist? Is it from model/controller(CI used here) or i hav to do smth different in java json parser?
codeIgniter controller:
$data = $this->member->view_members();
header('Content-Type: application/json');
echo json_encode($data);
CI model:
$queries = $this->db->get('members');
return $queries->result();
json:
[{ "id": "1",
"name": "Magalamind Industries",
"tableGroup": "Birgunj rising round table 20",
"email": "birgunj123#gmail.com",
"position": "Senior Member",
"address": "Birgunj",
"phn": "9876543234",
"date": "2016-05-03 15:53:51",
"active": "1"},
{ "id": "2",
"name": "Ram kumar Sharma",
"tableGroup": "Lalitpur round table 5",
"email": "ram#gmail.com",
"position": "Recent Member",
"address": "Patandhoka, lalitpur",
"phn": "9876567890",
"date": "2016-05-03 15:53:51",
"active": "1"}]
java json parse with error msg: java.util.Vector cannot be cast to java.util.ArrayList
ConnectionRequest connectionRequest = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map<String,Object> parsedData = jSONParser.parse(new InputStreamReader(input));
response = (ArrayList) parsedData.get("root"); //error msg: java.util.Vector cannot be cast to java.util.ArrayList
}
.........
}
The
jSONParser.parse(new InputStreamReader(input));
is the old parsing method (notice it is deprecated in the javadocs), it uses Hashtables and Vectors.
You need to use the
jSONParser.parseJSON(new InputStreamReader(input));
Which uses HashMap and ArrayList
I am new To JSon and i want to search the following json string and get the required output.
String:
{"status":"Success","code":"200","message":"Retrieved Successfully","reason":null,"
"projects":
[
{
"projectName": "example",
"users":
[
{
"userName": "xyz",
"executions":
[
{
"status": "check",
"runs":
[
{
"Id": "------",
"Key": "---"
}
],
"RCount": 1
}
],
"RCount": 1
}
],
"RCount": 1
},
Like that i have many projects and now , if i give projectname and username as input i wantt to get its status as output.
Is it possible?If yes how?
You may use JSONObject for this.
JSONObject json = new JSONObject(string);
JSONArray[] projectsArray = json.getJSONArray("projects");
for(int i = 0; i < projectsArray.length; ++i)
{
String projectName = projectsArray[i].getString("projectName");
...
}
Use the same method to get the users.
You can use gson library. Using gson convert your json string to Map and then you can iterate through map to get required item
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> myMap = gson.fromJson(jsonString, type);
You can use the Google gson to map your json data structure to a Java POJOs.
Example :
You can have Projects class containing list/array of Users.
Users class containing list/array of Executions and so on.
Gson library can easily map the json to these classes as objects and you can access your data in a more elegant manner.
Here are a few references :
http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
I'm new to JSON. I'm trying to create a JSON string in Java (org.json.JSONObject(json.jar)) which resembles like (basically a set of name-value pairs)
[{
"name": "cases",
"value": 23
}, {
"name": "revenue",
"value": 34
}, {
"name": "1D5",
"value": 56
}, {
"name": "diag",
"value": 14
}]
Can anyone help me on how to create this in Java? I want the name and value to be in each so that i can iterate over the collection and then get individual values.
The library is chained, so you can create your object by first creating a json array, then creating the individual objects and adding them one at a time to the array, like so:
new JSONArray()
.put(new JSONObject()
.put("name", "cases")
.put("value", 23))
.put(new JSONObject()
.put("name", "revenue")
.put("value", 34))
.put(new JSONObject()
.put("name", "1D5")
.put("value", 56))
.put(new JSONObject()
.put("name", "diag")
.put("value", 14))
.toString();
Once you have the final array, call toString on it to get the output.
What you've got there is a JSON array containing 4 JSON objects. Each object contains two keys and two values. In Java a JSON "object" is generally represented by some sort of "Map".
Try to use gson if you have to work a lot with JSON in java.
Gson is a Java library that can be used to convert Java Objects into JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Here is a small example:
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]
In java, I am trying to parse values from this json..
[
{
"2012-01-02": {
"age": 3,
"dob": "2010-01-03",
"name": "jack"
},
"2012-01-03": {
"age": 3,
"dob": "2010-01-04",
"name": "jill"
},
"2012-01-04": {
"age": 3,
"dob": "2010-01-05",
"name": "john"
},
"2012-01-05": {
"age": 3,
"dob": "2010-01-06",
"name": "miran"
}
}
]
Using JSONObject, I was trying to get the value of just "age" and then add them up to do some data manipulation.
I created a JSONObject
Created an iterator and then stored them to a map
This gets me the inner element like:
{
"age": 3,
"dob": "2010-01-06",
"name": "miran"
}
After this, not sure how to extract just age from each element. Do i create another jsonobject and pass this new string, extract age out of it or is there a better way to do this? (I am sure there is one)
UPDATE:
This is what I currently have that gives me {"age":3,"dob":"2012-01-06","name":"miran"}
JSONObject jsonobj = new JSONObject();
try {
jsonobj = new JSONObject(pastweekVol);
Iterator iter = jsonobj.keys();
Map<String, String> map = new HashMap<String, String>();
while(iter.hasNext()){
String jsonkey = (String)iter.next();
String value = jsonobj.getString(jsonkey);
logger.debug("first pass value is: {}", value);
} catch (JSONException je) {
logger.debug("exception is: {}",je);
}
I was thinking that since I am getting {"age":3,"dob":"2012-01-06","name":"miran"}, I would create another json object and pass in this string, which will give me value of "age". The problem here is that I get repetitive values. Of course, something very basic is missing here but I can't seem to figure that out.
If you have the inner element as a JSONObject instance - say person - then you can directly access the age:
int age = person.getInt("age");
and do something with it:
sum += age;
You might consider a library like Google's GSON (http://code.google.com/p/google-gson/) if you want to be able to easily parse arbitrarily complex JSON strnigs into generic objects.
Using org.json is probably not your best bet -- this API has many flaws. Using Jackson, you can easily extract age from each member value:
ObjectMapper mapper = new ObjectMapper();
JsonNode fullDocument = mapper.readTree(xxx); // xxx can be many things
// Not an object? Bail out
if (!fullDocument.isObject())
throw new IllegalArgumentException("not an object");
// This will iterate through object values
for (JsonNode value: fullDocument)
// do something with value.get("age")
// in particular, you can test for .isIntegralNumber()