如何使用杰克逊正确地反序列化.NET字典? [英] How do I correctly deserialize .NET Dictionaries using Jackson?

查看:185
本文介绍了如何使用杰克逊正确地反序列化.NET字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要帮助,如何使用杰克逊和自定义解串器反序列化字典。



现在我有一个与.NET(C#)服务器的Android应用程序通信。他们使用JSON进行通信。



在JAVA方面,我使用的是Jackson来处理JSON,而在.NET端我正在使用内置的DataContractSerializer我知道,ppl将开始评论我应该使用别的东西,但我不是这样... ;-))



问题是我从C#发送字典,我想要将它反序列化为JAVA方面的HashMaps,但是我没有找到一个很好的资源来解决这个问题。



我发送的一个字典的一个例子来自C#:

  //这里,对象设备是关键字,下面的int表示金额
[ DataMember]
public Dictionary< Equipment,int> EquipmentList {get;组;

仅供参考,C#中的Equipment对象:

  [DataContract] 
public class Equipment
{
[DataMember]
public uint Id {get;组; }
[DataMember]
public string Name {get;组;

public override bool Equals(object obj)
{
if(obj.GetType()!= this.GetType())
return false;
设备e =(设备)obj;
return e.Id == this.Id;
}
}

它在C#端正确地序列化为体面的JSON ,字典如下所示:

  // .... 
EquipmentList:[
{
Key:{
EquipmentId:123,
Name:MyName
},
Value:1
我已经添加了一个自定义序列化程序(CustomMapSerializer),它是一个自定义序列化程序(CustomMapSerializer)像这样:

  public static ObjectMapper mapper = new ObjectMapper(); 
private static SimpleDeserializers simpleDeserializers = new SimpleDeserializers();
private static StdDeserializerProvider sp = new StdDeserializerProvider();

public static void InitSerialization()
{
simpleDeserializers.addDeserializer(String.class,new CustomStringDeserializer());
simpleDeserializers.addDeserializer(Map.class,new CustomMapDeserializer());
sp.withAdditionalDeserializers(simpleDeserializers);
mapper.setDeserializerProvider(sp);
}

并像这样装饰字段:

  @JsonDeserialize(using = CustomMapDeserializer.class)
public Map< Equipment,Integer>设备清单;

最后,当我运行它时,我会在定制的deserializer类中休息一下,但我不知道如何从这里进行:

  public class CustomMapDeserializer extends JsonDeserializer< Map> {

@Override
public Map deserialize(JsonParser arg0,DeserializationContext arg1)throws IOException,JsonProcessingException
{
return new HashMap< Object,Object>(); //< - 我可以在这里打破
}
}

所以,我想要的是一些关于如何创建一个具有正确值的HashMap的输入,即反序列化的设备作为键值和Int值。


$ b任何人可以帮助谁? =)

解决方案

好的,经过一段时间的测试和研究,这是我想出来的。
$ b

自定义解串器如下所示:

  public class CustomMapCoTravellerDeserializer extends JsonDeserializer< Map> {

@Override
public Map deserialize(JsonParser jp,DeserializationContext arg1)throws IOException,JsonProcessingException
{
HashMap&CoTravellers,Integer& myMap = new HashMap&CoTravellers,Integer>();

CoTravellers ct = new CoTravellers();

jp.nextToken(); // {
jp.nextToken(); // Key
jp.nextToken(); // {
jp.nextToken(); //CoTravellerId
jp.nextToken(); // CoTravellerId Id
int coTravellerValue = jp.getIntValue();
jp.nextToken(); // Name
jp.nextToken(); //名称值
String coTravellerName = jp.getText();
jp.nextToken(); //}
jp.nextToken(); //Value
jp.nextToken(); //值
int nbr = jp.getIntValue();



ct.CoTravellerId = coTravellerValue;
ct.Name = coTravellerName;

myMap.put(ct,nbr);


返回myMap;

}
}

我认为这将工作,如果我只能弄清楚我正在获得的JsonMappingException ...但是我会分别发布=)


to sum it up before the wall of text below :-)

I need help with how to deserialize a Dictionary using Jackson and a custom deserializer.

Right now I have an Android app communication with a .NET (C#) server. They use JSON to communicate.

On the JAVA-side, I am using Jackson to handle the JSON and on the .NET-side I am using the built in DataContractSerializer (I know, ppl will start commenting I should use something else, but Im not so... ;-) )

The problem is that I am sending Dictionaries from C# and I want that to be deserialized to HashMaps om the JAVA-side, but I havent found a good resource for how to do that.

One example of a Dictionary I am sending from C#:

// Here, the object Equipment is the key, and the int following indicates the amount
[DataMember]
public Dictionary<Equipment, int> EquipmentList { get; set; }

And just for reference, the Equipment object in C#:

[DataContract]
public class Equipment
{
    [DataMember]
    public uint Id { get; set; }
    [DataMember]
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        if (obj.GetType() != this.GetType())
            return false;
        Equipment e = (Equipment)obj;
        return e.Id == this.Id;
    }
}

Its serialized correctly into decent JSON on the C#-side, the Dictionary looks like this:

//....
"EquipmentList":[
   {
      "Key":{
         "EquipmentId":123,
         "Name":"MyName"
       },
       "Value":1
   }
//....

I have added a custom serializer (CustomMapSerializer), like this:

public static ObjectMapper mapper = new ObjectMapper();
private static SimpleDeserializers simpleDeserializers = new SimpleDeserializers();
private static StdDeserializerProvider sp = new StdDeserializerProvider();

public static void InitSerialization()
{
    simpleDeserializers.addDeserializer(String.class, new CustomStringDeserializer());
    simpleDeserializers.addDeserializer(Map.class, new CustomMapDeserializer());
    sp.withAdditionalDeserializers(simpleDeserializers);
    mapper.setDeserializerProvider(sp);
}

And decorated the field like this:

@JsonDeserialize(using=CustomMapDeserializer.class)
public Map<Equipment, Integer> EquipmentList;

And finally, when I run it I do get a break in the custom deserializer class, but I am not sure how to proceed from here:

public class CustomMapDeserializer extends JsonDeserializer<Map> {

    @Override
    public Map deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException, JsonProcessingException 
    {
        return new HashMap<Object, Object>(); // <-- I can break here
    }   
}

So, what I would like is some input on how to create a HashMap with the correct values in it, ie a deserialized Equipment as Key and an Int as value.

Anyone out there who can assist? =)

解决方案

Ok, after a while testing and researching, this is what I came up with.

The custom deserializer looks like this:

    public class CustomMapCoTravellerDeserializer extends JsonDeserializer<Map> {

    @Override
    public Map deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException 
    {
        HashMap<CoTravellers, Integer> myMap = new HashMap<CoTravellers, Integer>();

            CoTravellers ct = new CoTravellers();

            jp.nextToken(); // {
            jp.nextToken(); // Key
            jp.nextToken(); // {
            jp.nextToken(); // "CoTravellerId"
            jp.nextToken(); // CoTravellerId Id
            int coTravellerValue = jp.getIntValue();
            jp.nextToken(); // Name
            jp.nextToken(); // Name Value
            String coTravellerName = jp.getText();
            jp.nextToken(); // }
            jp.nextToken(); // "Value"
            jp.nextToken(); // The value
            int nbr = jp.getIntValue();



            ct.CoTravellerId = coTravellerValue;
            ct.Name = coTravellerName;

            myMap.put(ct, nbr);


            return myMap;

    }   
}

I think this will work, if I can only figure out the JsonMappingException I am getting... but I will post on that separately =)

这篇关于如何使用杰克逊正确地反序列化.NET字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆