I have this JSON request
{
"status": "completed",
"test":"hi",
"order":{
"name":"book",
"qty":"2"
},
"customer":{
"name":"sajid",
"address":"salmiya"
},
"products":{
"name":"abc",
"qty":"1"
}
}
I have already Deserialized JSON using this
Dictionary<string, object> values = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(test);
But I am unable to get the values of product name and quantity
and similar way I want the values for customer.
In your dictionay a key is a string type, but a value is JObject. To get data you have to cast a dictionary value to JObject
Dictionary<string, object> values = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(test);
Dictionary<string,string> products =((JObject) values["products"]).ToObject<Dictionary<string,string>>();
//or
var products = (JObject) values["products"];
var productName= products["name"];
var productQty = products["qty"];
// or directly
productName= (string) ((JObject) values["products"])["name"];
productQty = (string) ((JObject) values["products"])["qty"];
Related
I am working on a Food Delivery App in Flutter and I have a list of model objects in my cart System. I need to send this list to API in JSON format so I convert that to JSON before sending it to server but i am getting error:
errors: {: [Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Metronic.Models.FoodOrderInsert' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I am beginner in Flutter and your kind response will highly be appreciated.
I am currently converting list and sending it to API like this:
I have my List of modelbjects:
List<FoodDetail> foodOrderDetails = [...]
var jsonObjectsList = [];
//Here I convert my list of FoodDetails into list of jsonObjects
for (var item in foodOrderDetail) {
jsonObjectsList.add(item.toJson());
}
await http
.post(
Uri.parse(url),
headers: ApiURLs.header,
body: jsonEncode(jsonObjectsList)
)
And my API required data is:
[{
"OrderId": 0,
"ProductId": 0,
"Quantity": 0,
"Price": 0}]
my FoodDetail class contain same these properties and converted to json but the problem I think is in conveting whole list to json.
i suggestion to use DIO lib its automatically convert your data to json
check it: https://pub.dev/packages/dio
use this class to parse the server response
FoodExample foodExample=FoodExample.fromJson(jsonEncode(jsonObjectsList))
with this line you will have access to all the attributes of the class
class FoodExample {
int orderId;
int productId;
int quantity;
int price;
FoodExample({this.orderId, this.productId, this.quantity, this.price});
FoodExample.fromJson(Map<String, dynamic> json) {
if(json["OrderId"] is int)
this.orderId = json["OrderId"];
if(json["ProductId"] is int)
this.productId = json["ProductId"];
if(json["Quantity"] is int)
this.quantity = json["Quantity"];
if(json["Price"] is int)
this.price = json["Price"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["OrderId"] = this.orderId;
data["ProductId"] = this.productId;
data["Quantity"] = this.quantity;
data["Price"] = this.price;
return data;
}
}
I solved my question by using Dio package,
That was the error due to http package internal code.
My Method for posting list to Server:
Future<int> insertFoodOrderDetails(List<FoodOrderDetail> foodOrderDetail) async {
var dio = Dio();
var mapData;
var url = ApiURLs.baseUrl + ApiURLs.insertFoodOrderDetails;
var jsonObjectsList = [];
for (var item in foodOrderDetail) {
jsonObjectsList.add(item.toMap());
}
await
dio.post(
url,
queryParameters: ApiURLs.header,
data: jsonObjectsList
)
.then((value) {
mapData = value.data as Map<String, dynamic>;
});
if (mapData['Status'] == 'Inserted Successfully') {
print(mapData['Id']);
return mapData['Id'] ;
}
else{
return 0;
}
}
I am writing a web service-REST.
I am receiving a text_plain format.
Example of my data:
{"data_log":
{
"methodClass": [{"methodName": 1, "methodStatus": "1"},
{"methodName": 2, "methodStatus": "1"}]
}
}
In my Restful Webservice, I try to read the data, but I got error 500 Internal Server Error-JSON Object not found.
public int adaptiveAuth(String objDataLog){
logWriter("objDataLog:"+objDataLog);
JSONObject obj = new JSONObject(objDataLog);
JSONArray methodClassObj=(JSONArray)obj.get("methodClass");
if (methodClassObj != null) {
JSONObject methodObj;
String entrymethodName, entrymethodStatus;
for (Object o : methodClassObj) {
methodObj = (JSONObject) o;
entrymethodName = String.valueOf(methodObj.get("methodName"));
entrymethodStatus = String.valueOf(methodObj.get("methodStatus"));
logWriter("entrymethodName:"+entrymethodName);
logWriter("entrymethodStatus:"+entrymethodStatus);
}
}
}
I already tried to use the below code, but it still give me the error.
String methodClass= obj.getJSONObject("data_log").getString("methodClass");
I'm expecting to put the current data into an 2 dimension array which it would be like this:
[1,1],[2,1]
Anyone could give me some suggestion on how to solve this issue?
**Try this code for parsing json data**
ArrayList<HashMap<String, String>> list;
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray b= jsonObj.getJSONArray("methodClass");
// looping through All data
for (int i = 0; i < b.length(); i++) {
JSONObject c = b.getJSONObject(i);
String entrymethodName = c.getJSONObject("methodClass").getString("methodName");
String entrymethodStatus = c.getJSONObject("methodClass").getString("methodStatus");
// tmp hash map for storing values
HashMap<String, String> co = new HashMap<>();
// adding each child node to HashMap key => value
co.put(entrymethodName, entrymethodStatus );
// adding co to list
list.add(co);
Also check this - https://gist.github.com/codebutler/2339666
I changed by String to this format:
{ "methodSet": [
{
"methodName": 1,
"methodStatus": "1"
},
{
"methodName": 2,
"methodStatus": "1"
}
]
}
and for the code :
ArrayList<String> listMethod = new ArrayList<String>();
JSONArray arr=(JSONArray)obj.get("methodClass");
if (arr != null) {
JSONObject objMethod;
String MethodName, MethodStatus;
for (Object o : arr) {
objMethod = (JSONObject) o;
MethodName = String.valueOf(objMethod.get("methodName"));
MethodStatus = String.valueOf(objMethod.get("methodStatus"));
int resultMethodName = Integer.parseInt(MethodName);
int resultMethodStatus = Integer.parseInt(MethodStatus);
logWriter("MethodStatus"+resultMethodName);
logWriter("MethodName"+resultMethodStatus);
listMethod.add("(" + MethodName + "," + MethodStatus + ")");
logWriter("listMethod is : "+listMethod);
}
}
I have a use case where an API will get a generic collection of Key|Value pairs in json. There are no defined attributes in the input json. I need to map it to a generic object and process the data..
JSON input:
"[{ "PostalCode": "345", "Region": "MA", "Enabled": "True" },
{"PostalCode": "989", "Country": "US", "Enabled": "True" }
]";
I am using GSON to deserialize this to java object. On mapping this to a generic object like:
Object obj = new GsonBuilder().create()
.fromJson(jsonInput, Object.class);
i get a an object of Array list of HashMaps (com.google.gson.internal.LinkedTreeMap).
From here how do i get individual key and values like key = PostalCode & value = 345?
Thanks in advance for your help!
As you have already got an array list of com.google.gson.internal.LinkedTreeMap, Now you need to iterate this list to get each key value pair :
Object obj = new GsonBuilder().create().fromJson(jsonInput, Object.class);
List<LinkedTreeMap<Object, Object>> jsonMapList = (List<LinkedTreeMap<Object, Object>>) obj;
for (LinkedTreeMap<Object, Object> jsonMap : jsonMapList) {
Set<Entry<Object, Object>> entrySet = jsonMap.entrySet();
for (Entry<Object, Object> entry : entrySet) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
You can do this way. I have tested it.
import this
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
Type type = new TypeToken<List<LinkedTreeMap<Object, Object>>>(){}.getType();
List<Map<Object, Object>> treeMap = newGsonBuilder().create().fromJson(jsonInput,type);
I am trying to parse this json in android and displaying the contents in list.
I am able to retrieve title,location and creator but dont know how to get inside des_update and retrieve text on '0'
[
{
"title": "my event ",
"location": "Chennai, Tamil Nadu, India",
"creator": "abc",
"des_update": {
"0": "this is my event with moderator"
}
},
{
"title": "my event 17",
"location": "pune",
"creator": "abc",
"des_update": {}
}
]
this is my parsing code I want to display data in alist
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<events> apps = new ArrayList<events>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
events app = new events();
app.setTitle(json.getString("title"));
app.setDate(json.getString("date"));
app.setLocation(json.getString("location"));
// add the app to apps list
apps.add(app);
...
}
you can use the following code:
JSONArray jsonArray = new JSONArray(json);
JSONObject object = jsonArray.getJSONObject(0);
JSONObject desObject = object.getJSONObject("des_update");
String data = desObject.getString("0");
System.out.println(data);
Here first you are loading your json string into JSONArray, and then you are taking one object from JSONArray instance. As des_update is an object with in the object you need to get that object calling getJSONObject() by passing your key and from there you can load the data that you want to use.
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String title = object.getString("title");
String location = object.getString("location");
String creator = object.getString("creator");
JSONObject des_update = object.getJSONObject("des_update");
String str = des_update.getString("0");
System.out.println("des_update-------" + str);
}
I'm trying to create a json string of the following format in WP8
{"user": { "email": "abc#gmail.me", "password": "abc"}}
I have created { "email": "abc#gmail.me", "password": "abc*"} part like
string emailText = confirmEmailTbox.Text;
string passText = "password";
string pass = confirmPasswordPBox.Password;
Dictionary<string, string> jsonChild = new Dictionary<string, string>();
jsonChild.Add(emailText, email);
jsonChild.Add(passText, pass);
string jsonStringChild = JsonConvert.SerializeObject(jsonChild, Formatting.None);
But how do i put all this into the other object as in how do i add the "user" to the
jsonString
Edit: Both formats
{
"user": {
"email": "abc#gmail.me"
"password": "12345"
}
}
Leverage the anonymous objects available in C#:
var data = new { user = new { email=email, password = pass}};
string jsonStringChild = JsonConvert.SerializeObject(data);