How to creation of multiple json arrays at a go? - arrays

I need to create multiple Json arrays at a single instance. I have 38 rows. For 38 rows first I need to create 38 empty JSON arrays. Then in each JSON array i need to add first column of row as first object in all the arrays. Second column as 2nd object etc. Is there a way to specify the position to add the objects in each array?
[
[
{
"fileName": "123"
},
{
"id": "100"
},
{
"product": ""
}
],
[
{
"fileName": "123"
},
{
"id": "100"
},
{
"product": ""
}
]...38
]

package emp;
import javax.lang.model.element.PackageElement;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Temp
{
public static void main(String[] args) throws JSONException {
JSONArray jsonArray = new JSONArray();
jsonArray.put(createJsonArray("name 1", "id 1", "product 1"));
jsonArray.put(createJsonArray("name 2", "id 2", "product 2"));
jsonArray.put(createJsonArray("name 3", "id 3", "product 3"));
System.out.println(jsonArray.toString());
}
public static JSONArray createJsonArray(String name, String id, String product) throws JSONException
{
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("fileName", "123");
jsonArray.put(jsonObject);
jsonObject.put("id", "123");
jsonArray.put(jsonObject);
jsonObject.put("product", "product");
jsonArray.put(jsonObject);
return jsonArray;
}
}

Related

What is the best way to parse the below json structure using gson model or model class

Is there any best way to parse the below JSON structure:
[{
"0": {
"state": {
"type": "A",
"stat": "ready"
},
"nodes": {
"type": "B",
"state": "ready"
}
},
"1": {
"state": {
"type": "C",
"state": "ready"
},
"nodes": {
"type": "D",
"state": "ready"
}
},
"2": {
"state": {
"type": "C",
"state": "ready"
},
"nodes": {
"type": "D",
"state": "ready"
}
}
}]
I have used the below code to parse.
List<LinkedTreeMap<String, Map<String, Map<String, String>>>> result = new GsonBuilder().create().fromJson(restResponse.getBody(),ArrayList.class);
Is there any efficient way to parse ?
Please help.
Is it mandatory to use Gson for this ? I feel like Jackson will be more efficient for parsing, kinda like so:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
// create instance of objectMapper:
ObjectMapper mapper = new ObjectMapper();
// define the java type you want to be parsed:
TypeReference<List<LinkedTreeMap<String, Map<String, Map<String, String>>>>> typeRef = new TypeReference<List<LinkedTreeMap<String, Map<String, Map<String, String>>>>>() {};
// use objectMapper's value to parse the data:
List<LinkedTreeMap<String, Map<String, Map<String, String>>>> result = mapper.readValue(restResponse.getBody(), typeRef);
Now, if it's mandatory to use Gson, I'd try to improve the performance a little, for example using JsonReader class to parse the data incrementally, thus optimizing memory usage:
import com.google.gson.stream.JsonReader;
import java.io.StringReader;
// creating insance of the JsonReader class and passing it to JSON as StringReader
JsonReader reader = new JsonReader(new StringReader(restResponse.getBody()));
// using beginArray:
reader.beginArray();
// loop to read the elements in the array
while (reader.hasNext()) {
// beginObject to start reading
reader.beginObject();
// use nextName and nextString methods to read each field in the object currently:
String name = reader.nextName();
String value = reader.nextString();
// make some changes with the name and value
// finish reading the current object:
reader.endObject();
}
// finish reading the array:
reader.endArray();

Cannot deserialize out of start_array token

This is my method for POST test
public void createParagraph3() {
RestAssured.baseURI = paragraphsURL;
Map<String, Object> map = new HashMap<String, Object>();
map.put("featurePackage", Arrays.asList(new HashMap<String, String>() {{
put("name", "Test");
put("inputText", "test test");
}}));
map.put("features", Arrays.asList(new HashMap<String, Object>() {{
put("featureType", "Feature");
put("inUse", "true");
put("name", "test xyxy");
}}));
map.put("type", Arrays.asList(new HashMap<String, String>() {{
put("key", "int");
put("name", "Introduction");
}}));
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
request.body(map).toString();
Response response = request.post();
int statusCode = response.getStatusCode();
System.out.println("Response body: " + response.body().asString());
System.out.println("Status code received: " + statusCode);
}
Below I have my request on basis I'm creating my test
{
"featurePackage": {
"features": [
{
"featureType": "string",
"id": 0,
"inUse": true,
"name": "string"
}
],
"id": 0,
"name": "string",
"objectCount": 0
},
"features": [
{
"featureType": "string",
"id": 0,
"inUse": true,
"name": "string"
}
],
"id": 0,
"inputText": "string",
"objectCount": 0,
"outputHtmlText": "string",
"sourceFileName": "string",
"type": {
"key": "string",
"name": "string"
}
}
What I am doing wrong? I still received 400 response "Cannot deserialize instance". Can someone help? I have incomplete request in my method?
EDIT 1:
The root cause is that map.toString() is not a valid JSON string.
There are two ways for you to solve this problem:
use JSONObject instead of map, see this
convert map to JSON object, see this
PS: A demo about map.toString()
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
System.out.println(map.toString());
// get: {apple=1, banana=2} is NOT a valid JSON String
// but, {"apple":1,"banana":2} is a valid JSON String
EDIT 2:
Since the owner of question added some comments, I have to add the following answer.
Pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
Java code:
// your comment
Map<String, Object> titles = new HashMap<>();
titles.put("titles", Arrays.asList(new HashMap<String, Object>() {
{
put("id", "876");
put("title", "test");
}
}));
System.out.println(titles);
// my new answer
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(titles);
System.out.println(json);

How to convert String list to JSON Array Groovy

This is the problem that I'm trying to resolve. I have a list of map that I want to convert into JSON array in Groovy.
The list is:
List<Map<String, String>> studentList = [{id=1,name=John,email=john#google.com},{id=2,name=Peter,email=peter#google.com},{id=3,name=James,email=james#google.com}]
Desired JSON output is:
{
students: [{
"id" = "1",
"name" = "John",
"contact": {
"email": "john#google.com"
}
}, {
"id" = "2",
"name" = "Peter",
"contact": {
"email": "peter#google.com"
}
}, {
"id" = "3",
"name" = "James",
"contact": {
"email": "james#google.com"
}
}
]
}
My code only generates 1 student. Can anyone help me please?
def builder = new JsonBuilder()
for (Map student: studentList) {
builder.students {
id student.id
name student.name
contact {
email student.email
}
}
}
println builder.toPrettyString()
Appreciate your time and advice. Thank you.
Pass a list to the builder
You don't need to iterate through the list, you can pass a list to the builder,
using JsonBuilder's implicit call() method.
def builder = new JsonBuilder()
builder {
students builder( studentList )
}
public Object call( List list )
A list of elements as arguments to the JSON builder creates a root JSON array
See the JsonBuilder Groovydoc page for details of the various call()
methods.
Example code
In this example I've fixed up your map, and introduced a small Student class, to
simplify the code.
import groovy.json.JsonBuilder
class Student { int id; String name; String email }
studentList = [
new Student( id:1, name:'John', email:'john#google.com' ),
new Student( id:2, name:'Peter', email:'peter#google.com' ),
new Student( id:3, name:'James', email:'james#google.com' )
]
def builder = new JsonBuilder()
builder {
students builder( studentList )
}
println builder.toPrettyString()
Resulting JSON
{
"students": [
{
"id": 1,
"email": "john#google.com",
"name": "John"
},
{
"id": 2,
"email": "peter#google.com",
"name": "Peter"
},
{
"id": 3,
"email": "james#google.com",
"name": "James"
}
]
}
I have solved it with ff code.
def students = []
def builder = new JsonBuilder()
for (Map student: studentList) {
builder {
id student.id
name student.name
contact {
email student.email
}
}
students.add(builder.toString())
}
def jsonSlurper = new JsonSlurper()
def items = jsonSlurper.parseText(students.toString())
def json = new JsonBuilder()
json "students": items
println json.toPrettyString()

Problems parsing complex json in Flutter

I am having issues converting the following response ->
{
"data": [
{
"_id": "1AoJoWJ5Hdx3nZ5t",
"title": "Orange is the new black",
"imageUrl": "/1532353304050-oinb.jpg",
"likesCount": 674
},
{
"_id": "AeqiQJewtTvMPc1B",
"title": "X-Files",
"imageUrl": "/1532353346638-xfiles.png",
"likesCount": 6155
},
{
"_id": "gPkzfXoJXX5TuTuM",
"title": "Star Trek: Voyager",
"imageUrl": "/1532353336145-voyager.jpg",
"likesCount": 23
},
{
"_id": "vQBQcYwtF9GWWJyK",
"title": "South Park",
"imageUrl": "/1532353313669-southpark.jpg",
"likesCount": 56
},
{
"_id": "wjLUixBQ4sirMAYw",
"title": "The Simpsons",
"imageUrl": "/1532353326075-thesimpsons.jpg",
"likesCount": 65
}
]
}
I tried using the jsonserializer plugin as well as the json_annotations plugin but got nowhere.
I did try to get a parser class with quicktype.io but It seems to not work at all.
Can someone please guide me or assist me with this issue?
Thanks!
There is a good plugin for that in Android Studio.
JSON to Dart Class.
Once you install the plugin do as follow.
Press ALT + L
Give a Class Name and paste your JSON response
And you are done.
After you get a response do as follow as
import 'dart:convert';
var decodedData = json.decode(response.body);
var data = Data.fromJson(decodedData)
If you need the status code of you response then response.statusCode
I followed this official document of Flutter and it works for me.
https://flutter.dev/docs/development/data-and-backend/json
Follow these steps to solve your problem.
Add dependencies as shown in the document.
dependencies:
# Your other regular dependencies here
json_annotation: <latest_version>
dev_dependencies:
# Your other dev_dependencies here
build_runner: <latest_version>
json_serializable: <latest_version>
Create stackoverflow.dart
import 'package:json_annotation/json_annotation.dart';
part 'stackoverflow.g.dart';
#JsonSerializable()
class StackOverFlowModel {
#JsonKey(name: '_id')
String id;
String title;
String imageUrl;
int likesCount;
StackOverFlowModel();
factory StackOverFlowModel.fromJson(Map<String, dynamic> json) =>
_$StackOverFlowModelFromJson(json);
Map<String, dynamic> toJson() => _$StackOverFlowModelToJson(this);
}
Giving variable name as _id will confuse Dart with a private variable. It is better to give it a JSON name using JsonKey annotation.
Run flutter pub run build_runner build in the terminal.
stackoverflow.g.dart will be generated like this.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'stackoverflow.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
StackOverFlowModel _$StackOverFlowModelFromJson(Map<String, dynamic> json) {
return StackOverFlowModel()
..id = json['_id'] as String
..title = json['title'] as String
..imageUrl = json['imageUrl'] as String
..likesCount = json['likesCount'] as int;
}
Map<String, dynamic> _$StackOverFlowModelToJson(StackOverFlowModel instance) =>
<String, dynamic>{
'_id': instance.id,
'title': instance.title,
'imageUrl': instance.imageUrl,
'likesCount': instance.likesCount
};
For testing do this
Map map = {
"data": [
{
"_id": "1AoJoWJ5Hdx3nZ5t",
"title": "Orange is the new black",
"imageUrl": "/1532353304050-oinb.jpg",
"likesCount": 674
},
{
"_id": "AeqiQJewtTvMPc1B",
"title": "X-Files",
"imageUrl": "/1532353346638-xfiles.png",
"likesCount": 6155
},
{
"_id": "gPkzfXoJXX5TuTuM",
"title": "Star Trek: Voyager",
"imageUrl": "/1532353336145-voyager.jpg",
"likesCount": 23
},
{
"_id": "vQBQcYwtF9GWWJyK",
"title": "South Park",
"imageUrl": "/1532353313669-southpark.jpg",
"likesCount": 56
},
{
"_id": "wjLUixBQ4sirMAYw",
"title": "The Simpsons",
"imageUrl": "/1532353326075-thesimpsons.jpg",
"likesCount": 65
}
]
};
List<StackOverFlowModel> list = List.generate(map['data'].length,
(index) => StackOverFlowModel.fromJson(map['data'][index]));
print(list);

Get nested JSON object from a JSON Array

May i know how to get JSON object from an json array??
JSON:
[
{
"id": 1,
"user": {
"id": 20710,
"username": "abc",
"first_name": "",
"last_name": "",
},
"action": {
"name": "xxx",
"date": 19/01/01,
},
},
{
"id": 2,
"user": {
"username": "xyx",
"first_name": "xxx",
"last_name": "yyy",
},
"action": {
"name": "xxx",
"date": 19/05/01,
},
},]
I want to get username of these users in a list, but i cant get the value when i get this json from api as JSONArray.
My code:
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("Create Response", response.toString());
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = response;
try {
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
JSONObject c=response.getJSONObject(1);
String id = c.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
feeds_List.add(map);
}
}
I cannot use
JSONObject object=JsonArray.getJSONObject("user");
here,
it only accept int for getJSONObject("user"); if it is JSONArray
You can use like this also.Suppose response String is userInfo
ArrayList<String> usernames = new ArrayList<String>();
JSONArray userList = new JSONArray(userInfo);
for (int j = 0; j < userList.length(); j++) {
JSONObject userObject = new JSONObject(userList.getString(j));
String user = userObject.getString("user");
JSONObject usernameInfo = new JSONObject(user);
usernames.add(usernameInfo.getString("username"));
}
Try this, if not working please mention me in comment.

Resources