Hi I am passing an xml as string
<AbcDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Abc">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>
When I am trying creating Custom Model Binder for Web Api
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(json))
{
var jsonObject = (JObject) Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
The json string passing as an parameter to the below method is an xml as string
I am facing exception at Newtonsoft.Json.JsonConvert.DeserializeObject(json);
Exception Details:
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
You are getting an error because JsonConvert.DeserializeObject() expects JSON input, not XML. If you want to handle XML with a JObject, you'll need to convert the XML to JSON first. The JsonConvert class has a SerializeXmlNode() method for this purpose.
Demo:
class Program
{
static void Main(string[] args)
{
string json = #"
<AbcDto xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Abc"">
<Id>2</Id>
<Description>sample string 4</Description>
<Name>sample string 3</Name>
<PolicyId>c17f5b9f-c9bf-4a3a-b09b-f44ec84b0d00</PolicyId>
<Status>Active</Status>
<TimeZoneId>USCentral</TimeZoneId>
</AbcDto>";
// If the json string contains XML, convert it to JSON
if (json.TrimStart().StartsWith("<"))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(json);
json = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
}
// Now you can load the JSON into a JObject
var jsonObject = JObject.Parse(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
foreach (string name in jsonPropertyNames)
{
Console.WriteLine(name);
}
}
}
Output:
#xmlns:i
#xmlns
Id
Description
Name
PolicyId
Status
TimeZoneId
Related
I am new to testing and i am trying to write a unit test cases on a Flink Datastream which takes input a jsonobject and passes the json object to a processfuntion and it returns a valid or invalid jsonobject when certain rule conditions are met below is the junit test case, below i am trying to compare the output jsonobject from process function with the jsonobject of the input file
#Test
public void testcompareInputAndOutputDataJSONSignal() throws Exception {
org.json.JSONObject jsonObject = toJsonObject();
String input = jsonObject.toString();
String output = JSONDataStreamOutput();
assertEquals(mapper.readTree(input), mapper.readTree(output));
}
below is my toJSONObject and JSONDataStream meathods
public static JSONObject toJsonObject() throws IOException, ParseException {
JSONParser jsonParser = new JSONParser();
FileReader fileReader = new FileReader(getFileFromResources("input.json"));
JSONObject obj = (JSONObject) jsonParser.parse(fileReader);
return obj;
}
public String SignalDataStreamOutput() throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<JSONObject> validSignal = env.fromElements(toJsonObject())
.process(new JsonFilter());
String outputFolder = "output";
validSignal.writeAsText(outputFolder).setParallelism(1);
env.execute();
String content = new String(Files.readAllBytes(Paths.get("output.txt")));
return content;
}
What i am doing is i am converting a jsonfile to jsonobject using the toJSONObject method and sending to a data stream using SignalDataStreamOutput method which will intern send it to a process function in JsonFilter class and validate it against a set of rules and if it's valid it will return a jsonobject and when trying to access the jsonobject directly from stream i am getting value like org.apache.flink#994jdkeiri so i am trying to write the output to a file and trying to read it back to a string and comparing it in test method but this is a work around process and i found a link to use Mockito framework here i changed it to use json object like below
final Collector<JSONObject> collectorMock = (Collector<JSONObject>)Mockito.mock(JsonFilter.class);
final Context contextMock = Mockito.mock(Context.class);
#Test
public void testcompareInputAndOutputDataForValidSignal() throws Exception {
org.json.JSONObject jsonObject = convertToJsonObject();
Mockito.verify(collectorMock).collect(jsonObject);
}
but the above approach is also not working can you suggest me simplified approach to test the json object
I'm new to this, and I want to read JSON file imported with rest api and parse it with spring boot.
I worked with CSV file with his method :
#RequestMapping(value = "/import", method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("file") MultipartFile multipartFile) throws IOException {
String name = multipartFile.getOriginalFilename();
System.out.println("File name: "+name);
byte[] bytes = multipartFile.getBytes();
System.out.println("File uploaded content:\n" + new String(bytes));
return "file uploaded";
}
Now i want to parse a JSON File :
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
I have try it to parse this file with java and it works for me but I dont know how to get it with rest api
This method to parse te file JSON and it works
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException {
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
"D:/PFE 2018/testjsonfile.json"));
for (Object o : jsonArray) {
JSONObject person = (JSONObject) o;
String strName = (String) person.get("name");
System.out.println("Name::::" + strName);
String strCity = (String) person.get("city");
System.out.println("City::::" + strCity);
JSONArray arrays = (JSONArray) person.get("cars");
for (Object object : arrays) {
System.out.println("cars::::" + object);
}
String strJob = (String) person.get("job");
System.out.println("Job::::" + strJob);
System.out.println();
}
}
now how to reuse this methode with rest api
It depends what you want to do with your JSON (it's not entirely clear in your question).
In general, good practice with Spring Boot is to use Jackson either:
binding your JSON with a POJO if you expect your JSON to have a known format or
mapping your JSON in a tree.
Examples for the described behaviours can be found in this article for instance.
I am working in VS 2015 and c#.
I have a Json String which has a list of collections, each collection represents an object,
string wsjson =
"{
"customAttributes":
[{"description":"xxxxxxx","id":11,"value":"xxxxxxx"},{"description":"xxxxxxx","id":10,"value":"xxxxxxx"}],
"location":{"account":"xxxxxxx","cabinet":"xxxxxxx"},
"misc":{"approved":false,"archived":false,"deleted":false,"echo":true,"external":false,"favorite":false,"officialLocked":false,"signed":false},
"permissions":[{"xxxxxxx":true,"xxxxxxx":false,"edit":true,"noAccess":false,"share":true,"view":true}],
"standardAttributes":{"aclStatus":"xxxxxxx","created":"\/Date(xxxxxxx)\/","createdBy":"xxxxxxx","createdByGuid":"xxxxxxx","envId":"xxxxxxx","extension":"ndws","id":"xxxxxxx","modified":"\/Date(xxxxxxx)\/","modifiedBy":"xxxxxxx","modifiedByGuid":"xxxxxxx","name":"xxxxxxx","officialVer":1,"size":4,"syncMod":xxxxxxx,"url":"xxxxxxx","versions":1}}"
DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
I am getting an error. I tried to follow this (Deserializing Json String into multiple Object types) solution but I am getting error for this line as my jason data is in a string and no function to parse string.
var j = JArray.Parse(data);
Here is the visual image of the jason data.
Actual code block in my program is:
foreach (DataRow row in dataTable.Rows)
{
string wsjson = GetWorkspaceProfile(row[0].ToString());
DataSet wsdataSet = JsonConvert.DeserializeObject<DataSet>(wsjson);
DataTable wsdataTable = wsdataSet.Tables["standardAttributes"];
foreach (DataRow wsrow in wsdataTable.Rows)
{
cmbWorkspaceByCabinet.Items.Add(new KeyValuePair<string, string>(row["envId"].ToString(), wsrow["name"].ToString()));
}
}
Where GetWorkspaceProfile is a string type return function which return me JSON data as string like the image above.
public string GetWorkspaceProfile(string WorkspaceId)
{
string responseStr = "";
string url = "v1/Workspace/" + WorkspaceId + "/info";
RestType type = RestType.GET;
Boolean useXml = false;
RestRequest rr = FormRequest(type, url, useXml);
IRestResponse response;
try
{
response = executeRequest(rr);
responseStr = response.Content;
}
catch (Exception ex)
{
return null;
}
return responseStr;
}
JArray.Parse will not work, because you don't have a json array, it is an object. Also not the all values of that object are collections, for example location is also object, not a collection. You have some options to parse it
Parse root object into Dictionary
JsonConvert.DeserializeObject<Dictionary<string, string>>(wsjson)
then parse every value of the dictionary to array if value is array and to dictionary if value is object.
Create a C# class according to your json data and parse string directly into instance of that class
JsonConvert.DeserializeObject<JsonModel>(wsjson);
where JsonModel is the class you need to create.
You can use JArray and JToken to get the values you want using json path.
i have json string like this downbelow
{"0":{"in":"mmm","loc":"1234"},"1":{"in":"mmm","loc":"1234"}}
Now i need to parse them as like
in | loc
---------
mmm| 1234
mmm| 1234
So far i did
public with sharing class Search
{
public String strTag {get;set;}
public String strlocation {get;set;}
public String result {get;set;}
public PageReference find() {
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://test.3spire.net/index.php?in='+strTag+'&loc='+strlocation);
req.setMethod('GET');
//these parts of the POST you may want to customize
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
try {
res = http.send(req);
} catch(System.CalloutException e) {
system.debug('Callout error: '+ e);
result = ''+e;
}
Result results = (Result) JSON.deserialize(res.getBody(),ResultSet.class);
result = res.getBody();
system.debug(res.getBody());
return null;
}
public class ResultSet{
public List<Result> resultSet;
}
public class Result
{
public String ins;
public String loc;
}
}
But its returns
System.TypeException: Invalid conversion from runtime type Search.ResultSet to Search.Result
How can i solved this problem
Thanks in advance
You are calling JSON.deserialize(res.getBody(),ResultSet.class). The second parameter ResultSet is the Apex object type you want the result to be. But then you attempt to cast it to a type of Result instead.
Either do
Result results = JSON.deserialize(res.getBody(), Result.class);
or
ResultSet results = JSON.deserialize(res.getBody(), ResultSet.class);
In your case, based on the JSON it would seem you want the second option. However, your JSON doesn't quite match your ResultSet class either. Your JSON is a map, not a list. Also, there's a field mismatch between "in" and "ins". This JSON is what would match your ResultSet class:
{{"ins":"mmm","loc":"1234"},{"ins":"mmm","loc":"1234"}}
I need to generate the following json files using Javascript serializer,
1. {"components":[{"name":"AA"}]}
2. {"customfield_10222":[{"name":"xxx"},{"name":"yyyy"}]} // this custom field represents the additional notification persons.
I have to achieve this scenario using the below coding,
public List<AdditionalUsers> AdditionalNotification = new List<AdditionalUsers>();
public List<ComponentsDetails> Component = new List<ComponentsDetails>();
class AdditionalUsers
{
public string name;
}
class ComponentsDetails
{
public string name;
}
string[] a=new string[2]{"XXX","YYY"};
foreach (string additionalUser in a)
{
AdditionalNotification.Add(new AdditionalUsers() { name =additionalUser });
}
Component.Add(new ComponentsDetails() { name = "AA" });
var subFields = new Dictionary<string, object>();
subFields.Add("components", Component); // represents 1 json file
subFields.Add("customfield_10222", AdditionalNotification); // represents 2 json file
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize((Object)subFields);
Console.WriteLine(json);
The result like this
{
"components":[{"name": "AA"}],
"customfield_10222":[{"name":"XXX"},{"name":"YYY"}]
}