如何从json.net中的序列化json中获取所有值,c#

时间:2017-09-20 18:41:07

标签: c# json

使用Json.NET,c#,。Net 3.5。

假设我有以下json:

{
  "invoicenr": "315.80042",
  "invoiceid": 3474838,
  "invoicedate": "2017-09-20T00:00:00+02:00",
  "invoicetype": "C",
  "invoicemethod": "I",
  "invoicemailby": "M",
  "amountex": -0.01,
  "amountin": 0
}

我需要完全按照它们在json中出现的所有值来形成包含所有这些值的字符串。

所以结果应该是

"315.8004234748382017-09-20T00:00:00+02:00CIM-0.010"

JsonTextReader不会这样做,因为它返回不同的值:

"315.80042347483820-9-2017 0:00:00CIM-0,010"

示例json非常简单。在现实世界中,它更复杂,包含数组,对象。所以解决方案应该是普遍的。

任何想法?日Thnx。

1 个答案:

答案 0 :(得分:0)

我删除了我的第一个答案,因为我终于找到了一个更简单的解决方案。如果您只是设置一个不专门解释DateTime对象的选项,则可以使用this.customer。就是这样。

JsonTextReader

输出

public static string GetJsonProperties(string json)
{
    string outputString = "";
    JsonTextReader reader = new JsonTextReader(new StringReader(json));
    //don't do date conversion, but get them as their verbatim string.
    reader.DateParseHandling = DateParseHandling.None;
    while (reader.Read())
    {
        if (reader.Value != null)
        {
            //We are not interested in the name of properties..
            if (reader.TokenType != JsonToken.PropertyName)
                outputString += reader.Value;
        }
    }
    return outputString;
}

public static void Main(string[] args)
{
    string someJson = 
        "{ "+
        "  \"invoicenr\": \"315.80042\", " +
        "  \"invoiceid\": 3474838, " +
        "  \"invoicedate\": \"2017-09-20T00:00:00+02:00\"," +
        "  \"invoicetype\": \"C\", " +
        "  \"invoicemethod\": \"I\", " +
        "  \"invoicemailby\": \"M\"," +
        "  \"amountex\": -0.01," +
        "  \"amountin\": 0," +
        " \"someArray\" : [1,2,3]," +
        " \"subObj\": { \"a\":42, \"b\":1337} " +
        "}";

    Console.WriteLine(GetJsonProperties(someJson));
    Console.ReadLine();
}
相关问题