logo
down
shadow

JSon - custom key serialization of nested maps


JSon - custom key serialization of nested maps

By : Max Power
Date : November 19 2020, 03:01 PM
wish of those help I have a nested Map> for which I need a custom key serializer & deserializer (StructureNode contains references to other objects which are needed to function as key for this map). I used the following method for this: , You can fix this with
code :
public static class Bean{
    @JsonSerialize(using = MapStructureNodeKeySerializer.class)
    public Map<StructureNode, Map<String, String>> metadata;
}
public static class MapStructureNodeKeySerializer 
        extends JsonSerializer<Map<StructureNode, Object>> {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void serialize(Map<StructureNode, Object> value, JsonGenerator gen, 
                          SerializerProvider serializers) throws IOException {
        gen.writeStartObject();

        for(Map.Entry<StructureNode, Object> val: value.entrySet()){
            // your custom serialization code here
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, val.getKey().copyUpwards());

            gen.writeObjectField(writer.toString(), val.getValue());
        }

        gen.writeEndObject();
    }
}
public static class Bean{
    @JsonSerialize(keyUsing = StructureNodeKeySerializer.class)
    public Map<StructureNode, Map<String, String>> metadata;
}
public static class StructureNodeKeySerializer extends JsonSerializer {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void serialize(Object value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {

        if (value instanceof StructureNode){ // <= type of 1-st level Map key
            // your custom serialization code here
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, ((StructureNode)value).copyUpwards());
            gen.writeFieldName(writer.toString());
        }else if(value instanceof String){   // <= type of 2-nd level Map key
            gen.writeFieldName((String) value);
        }
    }
}


Share : facebook icon twitter icon
IList and custom XML Serialization of nested objects

IList and custom XML Serialization of nested objects


By : Eisenhorn
Date : March 29 2020, 07:55 AM
it fixes the issue If you follow @Henk Holterman advice you also want to change the WriteXML on target to be
code :
writer.WriteAttributeString("Name",Name);
XmlSerializer xmlSerializer = new XmlSerializer(target.GetType());
xmlSerializer.Serialize(writer, target);
 <?xml version="1.0" encoding="utf-16" ?> 
<SerializeTarget>
  <Name /> 
 <Targets>
 <Target>
  <Target Name="foo" /> 
  </Target>
 <Target>
  <Target Name="foo2" /> 
  </Target>
 <Target>
  <Target Name="foo3" /> 
 </Target>
 </Targets>
</SerializeTarget>
Nested Dictionary objects json serialization

Nested Dictionary objects json serialization


By : user2979721
Date : March 29 2020, 07:55 AM
This might help you This is not a proper json or Python object. Python Lists cannot take named arguments. Only a dictionary can take key, value pairs. If you wish to go for a list, it has to be dictionaries added to the list and not as key value pairs. The items should be something like this:
List of dictionaries
code :
items = [
     {"name":"Chairs","options":{"type":"office","price":100}},
     {"name":"Tables","options":{"type":"office","price":45}},
]
items = {
      "first":{"name":"Chairs","options":{"type":"office","price":100}},
      "second":{"name":"Tables","options":{"type":"office","price":45}}
}
Golang custom JSON serialization (does something equivalent to gob.register() exist for json?)

Golang custom JSON serialization (does something equivalent to gob.register() exist for json?)


By : Kyle Fong
Date : March 29 2020, 07:55 AM
Hope that helps One thing you can do is using the json.RawMessage type and a custom Wrapper type. Then, upon receiving a message, you can do a switch (or use a map of constructors) to get the right struct.
For example (omitting error checking):
code :
package main

import (   
    "encoding/json"
    "fmt"  
)          

type Message struct {
    Type string
    Data json.RawMessage
}          

func (m Message) Struct() interface{} {
    unmarshaller, found := unmarshallers[m.Type]
    if !found {
        return nil
    }      
    return unmarshaller([]byte(m.Data))
}          

type Foo struct {
    ID int 
}          

var unmarshallers = map[string]func([]byte) interface{}{
    "foo": func(raw []byte) interface{} {
        var f Foo
        json.Unmarshal(raw, &f)
        return f
    },     
}          

func main() {
    var body = []byte(`{"Type":"foo","Data":{"ID":1}}`)
    var msg Message
    json.Unmarshal(body, &msg)

    switch s := msg.Struct().(type) {
    case Foo:
        fmt.Println(s)
    }      
}
Serialization of nested JSON with objects

Serialization of nested JSON with objects


By : user2971834
Date : March 29 2020, 07:55 AM
Any of those help It can be done in multiple ways but I followed what you did.
This is what I did:
code :
Imports Newtonsoft.Json

Public Class Form1

    Public Class Shipment
        Public Property ShipmentId As String
        Public Property BizId As String
        Public Property BizSalesOrder As Object
        Public Property Status As String
        Public Property OrderType As String
        Public Property OrderClass As String
        Public Property ShipmentLines As List(Of ShipmentLine)
        Public Property ShipAddress As ShipAddress
        Public Property ShipContacts As Object()
        Public Property ShipmentDespatch As Object()
    End Class

    Public Class ShipmentLine
        Public Property ShipmentId As String
        Public Property QtyOrdered As Double
        Public Property QtyRequired As Double
        Public Property QtyDueOut As Double
        Public Property SOLineId As Double
        Public Property Stage As String
    End Class

    Public Class ShipAddress
        Public Property Table As String
        Public Property ShipmentId As String
        Public Property AddressId As String
        Public Property Name As String
        Public Property Line1 As String
        Public Property Line2 As Object
        Public Property City As String
        Public Property Postcode As String
        Public Property Country As String
    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim NewShipment As New Shipment With {
            .ShipmentId = "111888",
            .BizId = "MORRIS",
            .BizSalesOrder = "null",
            .Status = "00",
            .OrderType = "S01",
            .OrderClass = "PACKSHIP"
        }
        Dim NewShipmentLines As New List(Of ShipmentLine)
        For x = 0 To 3
            Dim NewShipmentLine As New ShipmentLine
            NewShipmentLine.ShipmentId = "111888"
            NewShipmentLine.QtyOrdered = x
            NewShipmentLine.QtyDueOut = x
            NewShipmentLine.SOLineId = x
            NewShipmentLine.Stage = x
            NewShipmentLines.Add(NewShipmentLine)
        Next
        NewShipment.ShipmentLines = NewShipmentLines
        Dim NewShipAdress As New ShipAddress With {
            .Table = "SHH",
            .ShipmentId = "111888",
            .AddressId = "ADD1",
            .Name = "John Smith",
            .Line1 = "20 Michelin Ave",
            .Line2 = "null",
            .City = "LONDON",
            .Postcode = "A99 9BC",
            .Country = "GB"
        }
        NewShipment.ShipAddress = NewShipAdress
        NewShipment.ShipContacts = Nothing
        NewShipment.ShipmentDespatch = Nothing

        Dim ResultJSON As String = JsonConvert.SerializeObject(NewShipment).ToString
        Debug.Print(ResultJSON) '
    End Sub
End Class
{
   "ShipmentId":"111888",
   "BizId":"MORRIS",
   "BizSalesOrder":"null",
   "Status":"00",
   "OrderType":"S01",
   "OrderClass":"PACKSHIP",
   "ShipmentLines":[
      {
         "ShipmentId":"111888",
         "QtyOrdered":0.0,
         "QtyRequired":0.0,
         "QtyDueOut":0.0,
         "SOLineId":0.0,
         "Stage":"0"
      },
      {
         "ShipmentId":"111888",
         "QtyOrdered":1.0,
         "QtyRequired":0.0,
         "QtyDueOut":1.0,
         "SOLineId":1.0,
         "Stage":"1"
      },
      {
         "ShipmentId":"111888",
         "QtyOrdered":2.0,
         "QtyRequired":0.0,
         "QtyDueOut":2.0,
         "SOLineId":2.0,
         "Stage":"2"
      },
      {
         "ShipmentId":"111888",
         "QtyOrdered":3.0,
         "QtyRequired":0.0,
         "QtyDueOut":3.0,
         "SOLineId":3.0,
         "Stage":"3"
      }
   ],
   "ShipAddress":{
      "Table":"SHH",
      "ShipmentId":"111888",
      "AddressId":"ADD1",
      "Name":"John Smith",
      "Line1":"20 Michelin Ave",
      "Line2":"null",
      "City":"LONDON",
      "Postcode":"A99 9BC",
      "Country":"GB"
   },
   "ShipContacts":null,
   "ShipmentDespatch":null
}
How to do custom JSON serialization and deserialization in C#, when the object does not match the JSON

How to do custom JSON serialization and deserialization in C#, when the object does not match the JSON


By : user3487267
Date : March 29 2020, 07:55 AM
Hope this helps You can use Newtonsoft JSON.
First, add JsonProperty attributes to your classes:
code :
public class ClassA
{
  [JsonProperty("name")]
  public string Name { get; set; }

  [JsonProperty("objects")]
  public ClassB[] Objects { get; set; }
}
public class ClassBConverter : JsonConverter<ClassB> {
    ...

    public override void WriteJson(JsonWriter writer, ClassB value, JsonSerializer serializer)
    {
        writer.WriteValue((int)value.SomeEnum);
    }

    public override ClassB ReadJson(JsonReader reader, Type objectType, ClassB existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        int i = (int)((long) reader.Value);
        return new ClassB { SomeEnum = i };
    }
}
JsonConvert.(De)SerializeObject<ClassA>(yourJSONString, new ClassBConverter());
Related Posts Related Posts :
  • Interrupt CompletableFuture with default value
  • Eclipse - Choosing servers in "Run on server" vs setting "Target Runtime"
  • Spring JPA doesn't validate bean on update
  • How is takeWhile different from filter?
  • Spring Scheduled Cron jobs firing at wrong time
  • JFrame window resizing on every compile. Different results every time
  • Kotlin unresolved reference :add after converting from Java code
  • How to use Neo4j APOC method " apoc.export.csv.query(query,file,config)" in Java program
  • Regex to include all spanish characters and number
  • Parsing and Mapping a JSON Object with Dynamic Properties
  • Which approach to building domain objects in Spring MVC is more correct?
  • Java Long Min and Max not exact as mentioned in docs
  • Selenium opens new tab after SendKeys
  • How to sort a large array of ints?
  • FitNessse Test can not find Fixture
  • Including Signed Libraries in Executable JAR with Maven
  • If and Else statement run on second iteration of while loop
  • Change class of disabled tab on change of dropdown value
  • Junit5 @ParameterizedTest How to pass array as one of parameter
  • Text message not being sent to a list of numbers but is sent when just one number is specified
  • Spring mapped servlet not called in jetty-maven-plugin
  • How to pace the consumption of a sqs queue using spring integration
  • Autowiring Not getting disabled using xml configuration
  • Maze solve and shortest path with Java BFS
  • Spinner updating only on user actions
  • Why are Java rules for protected access such as they are?
  • Modify parameter of method by value in annotation aspectJ
  • How to send sensitive data to a Liferay portlet from outside the Liferay portal
  • Does a server connection stay open if created inside a method?
  • JAR manifest Class-Path, use folder instead of jar
  • How to do a bulk update in Firestore
  • ItemArray.checklist.add() not appending string to ArrayList
  • How to move something on screen without other picture staying there
  • SpringBoot : No matching bean found exception
  • Implementing the Clonable interface, but don't have to override the clone() method
  • how can i get this code to choose a random word once from each array to print a sentence?
  • Static class to get connections from connection pool
  • Unable to start Chrome browser with user profile in Selenium
  • How to pass a object to be created as a parameter for a method in Java?
  • How to retry with hystrix
  • Loading key to KeyStore fails on Android Oreo
  • Spring+Velocity unsuccessful attempts to save object
  • Private constructor in Kotlin
  • Jetty:run fails with NoSuchMethodError with Spring 5
  • Cannot upload my Web Applicartion in Jboss7 EAP7 EAP
  • How to load a certificate from "Credential storage"?
  • Call Genexus procedure stub in Java environment
  • JavaFX clipping produces a 'lottery scratch ticket'-Effect
  • Using DateTimeFormatter on january first cause an invalid year value
  • Get all the output from Watson conversation using java
  • Java unable to open main class and jar file
  • How to override @override method from activity into another class
  • Adding Runtime VM parameters to intellij for Java 9
  • Java IBM MQ Client connected but not getting messages from queue
  • Questions of Tomcat SSL configuration
  • Stale JNLP files for <extension> (since Java 9?)
  • Properly set (system) properties in JUnit 5
  • Spring MVC Model within POST Method is empty
  • VSTS buildagent: Java 9
  • java.lang.NumberFormatException: For input string: "id" for Hibernate
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org